How can I list all files of a directory in Python and add them to a list
?
os.listdir()
will get you everything that's in a directory - files and directories.
If you want just files, you could either filter this down 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. If you only want the top directory 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
I prefer using the glob
module, as it does pattern matching and expansion.
import glob print(glob.glob("/home/adam/*"))
It does pattern matching intuitively
import glob # All files and directories ending with .txt and that don't begin with a dot: print(glob.glob("/home/adam/*.txt")) # All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot: print(glob.glob("/home/adam/*/*.txt"))
It will return a list with the queried files and directories:
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
Note that glob
ignores files and directories that begin with a dot .
, as those are considered hidden files and directories, unless the pattern is something like .*
.
Use glob.escape
to escape strings that are not meant to be patterns:
print(glob.glob(glob.escape(directory_name) + "/*.txt"))
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