How to list all files in a directory in Python
In python, os.listdir() will list everything(files and directories) that is in a directory.
>>> import os
>>> os.listdir()
['DLLs', 'Doc', 'include', 'Lib', 'libs', 'LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'Scripts', 'tcl', 'Tools', 'vcruntime140.dll']
If you just want files only, you could filter the list like this,
>>> from os.path import isfile, join
>>> files_only = [file for file in os.listdir() if isfile(join(os.getcwd(),file))]
>>> files_only
['LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'vcruntime140.dll']
And also you could use os.walk(),
>>> (_,_,files) = next(os.walk(os.getcwd()))
>>> files
['LICENSE.txt', 'NEWS.txt', 'python.exe', 'python3.dll', 'python38.dll', 'pythonw.exe', 'vcruntime140.dll']
The os.walk() will walk through all the directories for a given path, in this case we only need the files directly under the given path, so we use next() built-in function to get the results. It generate one directory name and two lists (one for the directories, one for the filenames), so we only need the last one. So we write the code:
(_,_,files) = next(os.walk(os.getcwd()))
If you want pattern matching when listing files, you could use glob module,
>>> import glob
>>> glob.glob('*.txt')
['LICENSE.txt', 'NEWS.txt']
Comments
Post a Comment