Python 在具有部分字符串匹配的目录中查找文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37420624/
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
Find files in a directory with a partial string match
提问by LearningSlowly
I have a directory which contains the following files:
我有一个包含以下文件的目录:
apple1.json.gz
apple2.json.gz
banana1.json.gz
melon1.json.gz
melon2.json.gz
I wish to find all of the apple
, banana
and melon
file types.
我希望找到所有的apple
,banana
和melon
文件类型。
From this SO answerI know that I can find by file type by:
从这个SO answer我知道我可以通过以下文件类型找到:
import glob, os
os.chdir("/mydir")
for file in glob.glob("*.json.gz"):
print(file)
However, in my case I can't match by file name or file type. Rather it is a partial file name match (all apple
's and so on)
但是,就我而言,我无法按文件名或文件类型进行匹配。相反,它是部分文件名匹配(所有apple
的等等)
In this SO question, this solution was proposed:
在这个SO question 中,提出了这个解决方案:
[in] for file in glob.glob('/path/apple*.json.gz'):
print file
However, this returns zero
但是,这返回零
[out]
0
回答by Simon Fromme
Having the files in /mydir
as follows
文件/mydir
如下
mydir
├── apple1.json.gz
├── apple2.json.gz
├── banana1.json.gz
├── melon1.json.gz
└── melon2.json.gz
you could either do
你可以做
import glob
import os
os.chdir('/mydir')
for file in glob.glob('apple*.json.gz'):
print file
or
或者
import glob
for file in glob.glob('/mydir/apple*.json.gz'):
print file
Changing directories will not effect glob.glob('/absolute/path')
.
更改目录不会影响glob.glob('/absolute/path')
.
回答by Thom Ives
Double List Comprehension Method
双列表理解法
I was looking for a similar tool and developed a double list comprehension method that should work well for your case (I tested it for my case) ...
我正在寻找一个类似的工具并开发了一种双列表理解方法,它应该适合你的案例(我为我的案例测试了它)......
import os
def get_file_names_with_strings(str_list):
full_list = os.listdir("path_to_your_dir")
final_list = [nm for ps in str_list for nm in full_list if ps in nm]
return final_list
print(get_file_names_with_strings(['apple', 'banana', 'melon']))