繁体   English   中英

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

[英]Python - fnmatch function that lists files in a directory keeps previous contents

我试图将所有文件放在特定格式的特定目录(及其子目录)中。

我在这里找到了可以帮助我的代码,内容如下:

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))

filestotag是一个全局变量; 您可以在调用os.path.walk之前在listoffilestotaglistoffilestotag进行初始化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM