如何在 Python 中列出目录的所有文件并将它们添加到list?
如何在 Python 中列出目录的所有文件并将它们添加到list?
-
我更喜欢使用该
glob
模块,因为它可以进行模式匹配和扩展。import glob print(glob.glob("/home/adam/*"))
它直观地进行模式匹配
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"))
它将返回一个包含查询文件和目录的列表:
['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]
请注意,
glob
忽略以点开头的文件和目录.
,因为它们被视为隐藏文件和目录,除非模式类似于.*
.用于
glob.escape
转义不属于模式的字符串:print(glob.glob(glob.escape(directory_name) + "/*.txt"))
-
os.listdir()
将为您提供目录中的所有内容 -文件和目录。如果您只想要文件,您可以使用以下方式过滤
os.path
:from os import listdir from os.path import isfile, join onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
或者您可以使用
os.walk()
which 将为它访问的每个目录生成两个列表- 为您拆分为文件和目录。如果您只想要顶级目录,则可以在第一次产生时中断from os import walk f = [] for (dirpath, dirnames, filenames) in walk(mypath): f.extend(filenames) break
或者,更短:
from os import walk filenames = next(walk(mypath), (None, None, []))[2] # [] if no file