How do I list all files of a directory?

Explanation

Here we list all files of a directory

 If you want anything that is in the files or directories. You can use the os.listdir()  . By using this you will get everything that’s in a directory. 

 And in case if you want only files. So you can easily find this ust by using  os.path.

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

or you could use os.walk() which will yield two lists for each directory it visits – splitting into files and dirs for you. And if you want only the top directory at that time you can break the first time it yields

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

or, shorter:

from os import walk

filenames = next(walk(mypath), (None, None, []))[2]  # [] if no file

 

Also read, Write the SQL commands to accomplish this

Share this post

Leave a Reply

Your email address will not be published. Required fields are marked *