2015-11-05 118 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)