[英]Using fnmatch to match 2 parts of a file name
I am currently using fnmatch
to find the files that I want to copy and to ignore the rest: 我目前正在使用
fnmatch
查找要复制的文件,而忽略其余文件:
Below is some of my script just to give an example of how it's used. 以下是我的一些脚本,仅用于举例说明其用法。
pattern = "*.xlsx"
if fnmatch(name, pattern):
source_files.append(os.path.join(path, name))
What I've realised is that this is currently also matching hidden files, which I don't want copied. 我已经意识到,这目前也与隐藏文件匹配,我不想复制这些文件。
I see 3 options for solving this problem: 我看到解决此问题的3种选择:
~$
. ~$
开头的文件。 Update
and end with .xlsx
Update
开头并以.xlsx
结尾的文件 I feel that the easiest way to describe the type of files I want to copy is with regex but I don't think fnmatch accepts full regex. 我觉得描述我要复制的文件类型的最简单方法是使用正则表达式,但是我不认为fnmatch接受完整的正则表达式。
What would you recommend? 你会推荐什么?
Use fnmatch
's ability to exclude certain characters, also specified in the docs 使用
fnmatch
排除某些字符的功能,这也在文档中指定
In [33]: fnmatch('hello.xlsx', '[!~]*.xlsx')
Out[33]: True
In [34]: fnmatch('~hello.xlsx', '[!~]*.xlsx')
Out[34]: False
And as for the last comment in your question - if you feel the best way to describe your file is with regex, why not replace fnmatch
with re.match(...) is not None
? 至于问题中的最后一条评论-如果您觉得描述文件的最佳方法是使用正则表达式,为什么不用
re.match(...) is not None
替换fnmatch
re.match(...) is not None
? Do you have to use fnmatch
? 您必须使用
fnmatch
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.