我有一个文件夹ROOT和许多不同的文件夹(让我们假设N),为了简单起见,我称之为F1,F2等...
我需要使用这些文件夹中的文件.如果我只有一个文件夹,我知道我可以做:
os.chdir(".") #I'm workingo in ROOT
for filename in glob.glob("*.txt"):
#I can work with the i-th file...
Run Code Online (Sandbox Code Playgroud)
但我需要做的是像这样(伪代码):
os.chdir(".") #I'm working in ROOT
for F-i-th in ROOT: #for each folder in the ROOT main folder
for filename in F-i-th("*.txt"): #I select only the file with this extention
#process data inside i-th file
Run Code Online (Sandbox Code Playgroud)
我的意思是我需要进入第一个文件夹(F1)并处理所有文件(或者如果它可能是所有的.txt文件),之后我应该进入F2并处理所有文件....
os.walk将执行目录的递归并fnmatch.filter匹配文件名模式.简单的例子:
import os
import fnmatch
for path,dirs,files in os.walk('.'):
for f in fnmatch.filter(files,'*.txt'):
fullname = os.path.abspath(os.path.join(path,f))
print(fullname)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4859 次 |
| 最近记录: |