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

问题描述

将为您提供目录中的所有内容 -和。

如果您想要文件,您可以使用以下方式过滤

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?

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...