Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从子字符串中查找文件名_Python_String_File - Fatal编程技术网

Python 从子字符串中查找文件名

Python 从子字符串中查找文件名,python,string,file,Python,String,File,我有一个我保存的文件名列表,如下所示: filelist = os.listdir(mypath) 现在,假设我的一个文件类似于“KRAS\u p0146\u 3GFT\u something\u something.txt” 然而,我提前知道的是,我有一个名为“KRAS\u p0146\u 3GFT\u*”的文件。如何仅使用“KRAS\u p0146\u 3GFT””从文件列表中获取完整的文件名 作为一个简单的例子,我做了以下几点: mylist = ["hi_there", "bye_th

我有一个我保存的文件名列表,如下所示:

filelist = os.listdir(mypath)
现在,假设我的一个文件类似于“
KRAS\u p0146\u 3GFT\u something\u something.txt

然而,我提前知道的是,我有一个名为“
KRAS\u p0146\u 3GFT\u*
”的文件。如何仅使用“
KRAS\u p0146\u 3GFT”
”从文件列表中获取完整的文件名

作为一个简单的例子,我做了以下几点:

mylist = ["hi_there", "bye_there","hello_there"]
假设我有字符串
“hi”
。如何使其返回
mylist[0]=“你好”

谢谢

如果您的意思是“给我所有以前缀开头的文件名”,那么这很简单:

[fname for fname in mylist if fname.startswith('hi')]

如果您指的是更复杂的模式,例如,“some.*.\u file”匹配“some.\u good.\u file”和“some.\u bad.\u file”,那么请查看regex模块。

在第一个示例中,您可以使用
glob
模块:

mylist = ["hi_there", "bye_there","hello_there"]
partial = "hi"
[fullname for fullname in mylist if fullname.startswith(partial)]
import glob
import os
print '\n'.join(glob.iglob(os.path.join(mypath, "KRAS_P01446_3GFT_*")))
这样做而不是
os.listdir

第二个示例似乎与第一个(?)关系不大,但这里有一个实现:

mylist = ["hi_there", "bye_there","hello_there"]
print '\n'.join(s for s in mylist if s.startswith("hi"))

如果列表不是很大,您可以像这样进行每项检查

def findMatchingFile (fileList, stringToMatch) :
    listOfMatchingFiles = []

    for file in fileList:
        if file.startswith(stringToMatch):
            listOfMatchingFiles.append(file)

    return listOfMatchingFiles

有更多的“pythonic”方法可以做到这一点,但我更喜欢这种方法,因为它更具可读性。

可能是,也可能不是。取决于询问者是否知道发电机是什么以及产量是如何工作的。根据我的经验,这是很少有人知道的。