我在Windows 7中有一个文件夹,其中包含多个.txt
文件。 如何将该目录中的每个文件作为列表获取?
你可以使用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")]
这里所有的答案都没有解决一个问题,即如果你传递给 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")]
import os
import glob
os.chdir('c:/mydir')
files = glob.glob('*.txt')
os.chdir()
的作用是改变当前工作目录。考虑到 glob.glob(r'c:\mydir\*.txt')
,它会返回所有在 c:\mydir
目录下以 .txt
结尾的文件路径列表。 - John Machinimport fnmatch
import os
return [file for file in os.listdir('.') if fnmatch.fnmatch(file, '*.txt')]
>>> 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.。
a.dat b.dat...
而不是C:\DIRNAME\SUBDIR\a.dat ....
吗? - smci