小编典典

如何在 Python 中列出目录的所有文件并将它们添加到list?

python

如何在 Python 中列出目录的所有文件并将它们添加到list?


阅读 367

收藏
2022-01-15

共2个答案

小编典典

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
2022-01-15
小编典典

我更喜欢使用该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"))
2022-01-15