我想要获取特定格式的特定目录(及其子目录)中的所有文件。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