我正在尝试获取特定目录(及其子目录)中具有特定格式的所有文件。
我找到了一个可以帮助我的代码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”似乎保留了以前的内容。为什么?我该如何解决这个问题?请注意,我并不完全理解我编写的实现......
谢谢!
最佳答案
在您的代码中,您正在更新一个全局变量,因此对该函数的每次调用实际上都是一次又一次地更新相同的列表。最好将本地列表传递给 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))
关于Python - 列出目录中文件的 fnmatch 函数保留以前的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22669247/