如何在Python中列出目录中的所有文件并将其添加到列表中?
当前回答
def list_files(path):
# returns a list of names (with extension, without full path) of all files
# in folder path
files = []
for name in os.listdir(path):
if os.path.isfile(os.path.join(path, name)):
files.append(name)
return files
其他回答
我将提供一个示例单行,其中可以提供源路径和文件类型作为输入。代码返回带有csv扩展名的文件名列表。使用以防需要返回所有文件。这还将递归扫描子目录。
[y代表os.walk中的x(sourcePath)代表glob中的y(os.path.join(x[0],'*.csv'))]
根据需要修改文件扩展名和源路径。
我真的很喜欢adamk的回答,建议您使用来自同名模块的glob()。这允许您使用*s进行模式匹配。
但正如其他人在评论中指出的,glob()可能会被不一致的斜线方向绊倒。为了帮助实现这一点,我建议您在os.path模块中使用join()和expanduser()函数,也可以在os模块中使用getcwd()函数。
例如:
from glob import glob
# Return everything under C:\Users\admin that contains a folder called wlp.
glob('C:\Users\admin\*\wlp')
上面的情况很糟糕-路径已被硬编码,并且只能在Windows上在驱动器名称和硬编码到路径之间工作。
from glob import glob
from os.path import join
# Return everything under Users, admin, that contains a folder called wlp.
glob(join('Users', 'admin', '*', 'wlp'))
上面的方法效果更好,但它依赖于文件夹名Users,该文件夹名在Windows中常见,而在其他操作系统中不常见。它还依赖于具有特定名称admin的用户。
from glob import glob
from os.path import expanduser, join
# Return everything under the user directory that contains a folder called wlp.
glob(join(expanduser('~'), '*', 'wlp'))
这在所有平台上都非常有效。
另一个很好的例子,它可以在不同的平台上完美运行,并且做了一些不同的事情:
from glob import glob
from os import getcwd
from os.path import join
# Return everything under the current directory that contains a folder called wlp.
glob(join(getcwd(), '*', 'wlp'))
希望这些示例能帮助您了解在标准Python库模块中可以找到的一些函数的功能。
import os
os.listdir("somedirectory")
将返回“somedirectory”中所有文件和目录的列表。
我更喜欢使用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"))
这是我的通用函数。它返回文件路径列表而不是文件名,因为我发现这更有用。它有几个可选的参数,使其具有通用性。例如,我经常将其与pattern=“*.txt”或subfolders=True等参数一起使用。
import os
import fnmatch
def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
"""Return a list of the file paths matching the pattern in the specified
folder, optionally including files inside subfolders.
"""
match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
return [os.path.join(root, f)
for root, dirnames, filenames in walked
for f in filenames if match(f, pattern)]