简体   繁体   English

Python:filename包含String(metachar?)

[英]Python: filename contains String (metachar?)

I'm using os.walk(directory) to show recursively all the files from that directory. 我正在使用os.walk(目录)递归显示该目录中的所有文件。 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. 问题是我只需要在其名称中显示包含问题字符串的文件,并且还必须管理元字符。

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,我该如何使它工作呢?

You can use glob. 你可以使用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")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM