2014-03-26 31 views
1

我想要獲取特定格式的特定目錄(及其子目錄)中的所有文件。Python -fnmatch函數列出目錄中的文件保留以前的內容

我發現了一個代碼,可以幫助我here,即去如下:

from fnmatch import fnmatch 
import os, os.path 

def print_fnmatches(pattern, dir, files): 
    for filename in files: 
    if fnmatch(filename, pattern): 
     print os.path.join(dir, filename) 

os.path.walk('/', print_fnmatches, '*.mp3') 

我改變它一點適合我的需要。我創建了一個新的模塊,這些都是它的內容:

from fnmatch import fnmatch 
import os.path 

filestotag = [] 

def listoffilestotag(path): 
    os.path.walk(path, fnmatches, '*.txt') 
    return filestotag 

def fnmatches(pattern, direc, files): 
    for filename in files: 
     if fnmatch(filename, pattern): 
      filestotag.append(os.path.join(direc, filename)) 

從不同的模塊,我可以打電話給listoffilestotag(),它工作正常。

但是,當我第二次調用它時,似乎'filestotag'保留了其以前的內容。爲什麼?我怎麼能解決這個問題?請注意,我並不完全瞭解我寫的實現...

謝謝!

回答

2

在你的代碼中,你正在更新一個全局變量,所以每個對該函數的調用實際上都是再次更新同一個列表。更好地通過本地列表fnmatches

from fnmatch import fnmatch 
from functools import partial 
import os.path 

def listoffilestotag(path): 
    filestotag = [] 
    part = partial(fnmatches, filestotag) 
    os.path.walk(path, part, '*.txt') 
    return filestotag 

def fnmatches(lis, pattern, direc, files): 
    for filename in files: 
     if fnmatch(filename, pattern): 
      lis.append(os.path.join(direc, filename)) 
+0

祝福你,它的工作原理!非常感謝你! – Cheshie

0

filestotag是一個全局變量;您可以在致電os.path.walk之前將其初始化爲listoffilestotag

+0

謝謝@Scott。我已經嘗試過了,但是然後它返回[] ....(當我把'filestotag = []'同時放在全局和'listoffilestotag'的開始處......) – Cheshie

相關問題