Python - 列出目录中文件的 fnmatch 函数保留以前的内容

标签 python

我正在尝试获取特定目录(及其子目录)中具有特定格式的所有文件。

我找到了一个可以帮助我的代码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/

相关文章:

python - 使用正则表达式使用反斜杠分割字符串

python - 将位串 numpy 数组转换为整数基数 2 的最快方法

python - 关于在 matplotlib 中调整边距

python - 如何命名以 "s"结尾的列表变量

python - 来自数据库的硬编码变量

python - 使用 Bonobo-ETL 将字典写入 CSV

python - 删除迁移文件夹后重置 Alembic

python - 回溯 : AttributeError: Symbol not Found

python - 如何打印 4 个字节作为整数

python - ndb.get_multi(keys) 返回 None 的数组