Skip to main content
 首页 » 编程设计

python之获取更改当前工作目录后所有 ".txt"的文件列表

2024年10月25日8leader

我更改了当前工作目录,然后我想列出该目录中扩展名为 .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)