2015-11-05 169 views
1

浏览文件夹我有一个文件夹根目录和里面的许多不同的文件夹(假设N),为了简单起见我叫F1,F2等等...与蟒蛇

我需要的文件工作在这些文件夹内。 如果我只有一个文件夹,我知道我能做到:

os.chdir(".") #I'm workingo in ROOT 
for filename in glob.glob("*.txt"): 
    #I can work with the i-th file... 

但我需要做的就是这样的事情(如伪代码):

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 

我的意思是,我需要进入第一个文件夹(F1)并处理所有文件(或者如果有可能所有的.txt文件),之后我应该进入F2并处理所有文件....

+4

你只想['os.walk'](https://docs.python.org/2/library/os.html#os.walk)? – jonrsharpe

回答

3

os.walk将执行递归的目录和fnmatch.filter将匹配文件名p atterns。简单的例子:

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)