我想要獲取特定格式的特定目錄(及其子目錄)中的所有文件。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'保留了其以前的內容。爲什麼?我怎麼能解決這個問題?請注意,我並不完全瞭解我寫的實現...
謝謝!
祝福你,它的工作原理!非常感謝你! – Cheshie