簡體   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