我更改了当前工作目录,然后我想列出该目录中扩展名为 .txt
的所有文件。我怎样才能实现这个目标?
# !/usr/bin/python
import os
path = "/home/pawn/Desktop/projects_files"
os.chdir(path)
## checking working directory
print ("working directory "+ os.getcwd()+'\n')
现在如何列出当前目录 (projects_files) 中扩展名为 .txt
的所有文件?
最佳答案
使用glob
,这是对文件的通配符搜索,并且您也不需要更改目录:
import glob
for f in glob.iglob('/home/pawn/Desktop/project_files/*.txt'):
print(f)
关于python - 获取更改当前工作目录后所有带有 ".txt"的文件列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25833124/