Python:文件名包含字符串(元字符?)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36294712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: filename contains String (metachar?)
提问by Croc
I'm using os.walk(directory) to show recursively all the files from that directory. The thing is that i need to show only the files that contain an asked String in its name, and it has to manage metachars too.
我正在使用 os.walk(directory) 递归显示该目录中的所有文件。问题是我只需要显示名称中包含询问字符串的文件,它也必须管理元字符。
What i have now is:
我现在拥有的是:
for root, subdirs, files in os.walk(dir1):
for filename in files:
if substring in filename:
name_path = os.path.join(root,filename)
list.insert(END, name_path)
This works nicely, but if substring = *
, as i dont have files containing an ' * ', my list is empty.
这很好用,但是如果 substring = *
,因为我没有包含“*”的文件,我的列表是空的。
So, how do I get this to work if substring
contains a METACHAR?
那么,如果substring
包含 METACHAR ,我该如何让它工作?
回答by Brian
I think you are looking for fnmatch:
我认为您正在寻找 fnmatch:
https://docs.python.org/3/library/fnmatch.html#module-fnmatch
https://docs.python.org/3/library/fnmatch.html#module-fnmatch
回答by amyst
You can use glob. It's very handy and similar to find command in Linux.
您可以使用全局。它非常方便,类似于 Linux 中的 find 命令。
import glob
glob.glob("/home/user/*.txt")
Search in multiple subdirectories
在多个子目录中搜索
glob.glob("/home/user/*/*.txt")
or
或者
glob.glob("/home/user/logs?.txt")