2014-03-26 24 views
1

我想要获取特定格式的特定目录(及其子目录)中的所有文件。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'保留了其以前的内容。为什么?我怎么能解决这个问题?请注意,我并不完全了解我写的实现...

谢谢!

回答

2

在你的代码中,你正在更新一个全局变量,所以每个对该函数的调用实际上都是再次更新同一个列表。更好地通过本地列表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)) 
+0

祝福你,它的工作原理!非常感谢你! – Cheshie

0

filestotag是一个全局变量;您可以在致电os.path.walk之前将其初始化为listoffilestotag

+0

谢谢@Scott。我已经尝试过了,但是然后它返回[] ....(当我把'filestotag = []'同时放在全局和'listoffilestotag'的开始处......) – Cheshie

相关问题