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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:42:22  来源:igfitidea点击:

Python: filename contains String (metachar?)

pythoncontainsmetacharacters

提问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 substringcontains a METACHAR?

那么,如果substring包含 METACHAR ,我该如何让它工作?

回答by Brian

回答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")