在Windows目录中获取每个文件

29

我在Windows 7中有一个文件夹,其中包含多个.txt文件。 如何将该目录中的每个文件作为列表获取?


你需要文件列表(不是路径名),例如 a.dat b.dat... 而不是 C:\DIRNAME\SUBDIR\a.dat .... 吗? - smci
可能是重复的问题:如何列出目录中的所有文件? - smci
5个回答

26

你可以使用os.listdir(".")来列出当前目录(".")的内容:

for name in os.listdir("."):
    if name.endswith(".txt"):
        print(name)

如果你想要将整个列表作为Python列表来使用,可以使用 列表推导式:

a = [name for name in os.listdir(".") if name.endswith(".txt")]

16

这里所有的答案都没有解决一个问题,即如果你传递给 glob.glob() 一个Windows路径(例如C:\okay\what\i_guess\),它无法按预期运行。相反,你需要使用 pathlib

from pathlib import Path

glob_path = Path(r"C:\okay\what\i_guess")
file_list = [str(pp) for pp in glob_path.glob("**/*.txt")]

这个解决方案适用于Windows。但它在Linux中也能工作吗?我需要我的代码是可移植的。 - Plutonium smuggler
它适用于Linux。路径比Glob更具可移植性。 - Seanny123
1
最后一行更简单且更快速,可写成 file_list = list(glob_path.glob("**/*.txt")) - wisbucky

15
import os
import glob

os.chdir('c:/mydir')
files = glob.glob('*.txt')

10
os.chdir() 的作用是改变当前工作目录。考虑到 glob.glob(r'c:\mydir\*.txt'),它会返回所有在 c:\mydir 目录下以 .txt 结尾的文件路径列表。 - John Machin
@John Machin:完全正确,这是另一种方法。 - Hugh Bothwell
4
这也是一种不必要地改变现任主管之一的副作用的方式。 - John Machin
1
@JohnMachin:因为这就是问题所要求的:文件列表(而不是路径名)。 - smci

2
import fnmatch
import os

return [file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.txt')]

1
“return” 不是只在函数中使用吗? - kurumi

1
如果您只需要当前目录,请使用os.listdir。
>>> os.listdir('.') # get the files/directories
>>> [os.path.abspath(x) for x in os.listdir('.')] # gets the absolute paths
>>> [x for x in os.listdir('.') if os.path.isfile(x)] # only files
>>> [x for x in os.listdir('.') if x.endswith('.txt')] # files ending in .txt only

如果你需要递归地获取目录的内容,你还可以使用 os.walk。请参考 Python 文档中的 os.walk.


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接