Python中的Unix文件名通配符? [英] Unix filename wildcards in Python?
问题描述
Unix 文件名通配符如何在 Python 中工作?
How do Unix filename wildcards work from Python?
一个给定的目录只包含子目录,在每个子目录中都有(除其他外)一个名称以已知字符串结尾的文件,例如 _ext
.文件名的第一部分总是不同的,所以我需要使用这种模式来访问文件.
A given directory contains only subdirectories, in each of which there is (among others) one file whose name ends with a known string, say _ext
. The first part of the filename always varies, so I need to get to the file by using this pattern.
我想这样做:
directory = "."
listofSubDirs = [x[0] for x in os.walk(directory)]
listofSubDirs = listofSubDirs[1:] #removing "."
for subDirectory in listofSubDirs:
fileNameToPickle = subDirectory + "/*_ext" #only one such file exists
fileToPickle = pickle.load(open(fileNameToPickle, "rb"))
... do stuff ...
但是没有发生模式匹配.在 Python 下它是如何工作的?
But no pattern matching happens. How does it work under Python?
推荐答案
Shell 通配符模式在 Python 中不起作用.使用 fnmatch
或 glob
模块来解释通配符.fnmatch
解释通配符并让你匹配字符串,glob
在内部使用 fnmatch
和 os.listdir()
> 为您提供匹配文件名的列表.
Shell wildcard patterns don't work in Python. Use the fnmatch
or glob
modules to interpret the wildcards instead. fnmatch
interprets wildcards and lets you match strings against them, glob
uses fnmatch
internally, together with os.listdir()
to give you a list of matching filenames.
在这种情况下,我会使用 fnmatch.filter()
:
In this case, I'd use fnmatch.filter()
:
import os
import fnmatch
for dirpath, dirnames, files in os.walk(directory):
for filename in fnmatch.filter(files, '*_ext'):
fileNameToPickle = os.path.join(dirpath, filename)
fileToPickle = pickle.load(open(fileNameToPickle, "rb"))
如果您的结构只包含一个级别的子目录,您还可以使用一个 glob()
模式来表达这一点;表达式的路径中的*/
被扩展以匹配所有子目录:
If your structure contains only one level of subdirectories, you could also use a glob()
pattern that expresses that; the */
in the path of expression is expanded to match all subdirectories:
import glob
import os
for filename in glob.glob(os.path.join(directory, '*/*_ext')):
# loops over matching filenames in all subdirectories of `directory`.
这篇关于Python中的Unix文件名通配符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!