我保存的文件名列表如下:
filelist = os.listdir(mypath)
现在,假设我的一个文件类似于“KRAS_P01446_3GFT_SOMETHING_SOMETHING.txt
”。
但是,我提前知道的是我有一个名为“KRAS_P01446_3GFT_*
”的文件。如何仅使用“KRAS_P01446_3GFT_*
”从文件列表中获取完整文件名?
作为一个更简单的示例,我做了以下内容:
mylist = ["hi_there", "bye_there","hello_there"]
假设我有字符串“hi”
。我如何让它返回 mylist[0] = "hi_there"
.
谢谢!
最佳答案
在第一个示例中,您可以只使用 glob
模块:
import glob
import os
print '\n'.join(glob.iglob(os.path.join(mypath, "KRAS_P01446_3GFT_*")))
执行此操作而不是os.listdir
。
第二个示例似乎与第一个示例(X-Y problem?)关系不大,但这是一个实现:
mylist = ["hi_there", "bye_there","hello_there"]
print '\n'.join(s for s in mylist if s.startswith("hi"))
关于python - 从子字符串中查找文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11569432/