How do I get a list of all files (and directories) in a given directory in Python?
You can use the os. walk() method to get the list of all children of path you want to display the tree of. Then you can join the paths and get the absolute path of each file.
listdir() method gets the list of all files and directories in a specified directory. By default, it is the current directory. Beyond the first level of folders, os. listdir() does not return any files or folders.
This is a way to traverse every file and directory in a directory tree:
import os for dirname, dirnames, filenames in os.walk('.'): # print path to all subdirectories first. for subdirname in dirnames: print(os.path.join(dirname, subdirname)) # print path to all filenames. for filename in filenames: print(os.path.join(dirname, filename)) # Advanced usage: # editing the 'dirnames' list will stop os.walk() from recursing into there. if '.git' in dirnames: # don't go into any .git directories. dirnames.remove('.git')
You can use
os.listdir(path)
For reference and more os functions look here:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With