问题描述
将为您提供目录中的所有内容 -和。
from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]
或者您可以使用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
我更喜欢使用该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"))
解决方法
如何在 Python 中列出目录的所有文件并将它们添加到list?