Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/345.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.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 os.path.exists()忽略部分文件名_Python_File_Operating System - Fatal编程技术网

Python os.path.exists()忽略部分文件名

Python os.path.exists()忽略部分文件名,python,file,operating-system,Python,File,Operating System,我有一个如下所示的目录: > myDirectory > L1.zip > L2_abc.zip >>> file_exists("L1") true >>> file_exists("L2") true 我想搜索目录以返回文件是否存在,但我将只拥有zip文件名的第一部分(L1或L2)。我如何检查文件是否存在 结果应该有点像以下内容: > myDirectory > L1.zip >

我有一个如下所示的目录:

> myDirectory
    > L1.zip
    > L2_abc.zip
>>> file_exists("L1")
true 
>>> file_exists("L2")
true 
我想搜索目录以返回文件是否存在,但我将只拥有zip文件名的第一部分(L1或L2)。我如何检查文件是否存在

结果应该有点像以下内容:

> myDirectory
    > L1.zip
    > L2_abc.zip
>>> file_exists("L1")
true 
>>> file_exists("L2")
true 

我目前正在使用
os.path.exists()
,但我不知道如何忽略文件名的
\u abc
部分。

您可以使用listdir并进行自定义检查。这里有一种方法仅在file/dir以L2开头时匹配

matches = [f for f in os.listdir() if f.startswith("L2")]
print(matches)

您可以使用listdir并进行自定义检查。这里有一种方法仅在file/dir以L2开头时匹配

matches = [f for f in os.listdir() if f.startswith("L2")]
print(matches)
使用,并检查结果输出是否为空,这样可以:

from glob import glob

def file_exists(filename):
    return bool(glob(filename + '.*'))
使用,并检查结果输出是否为空,这样可以:

from glob import glob

def file_exists(filename):
    return bool(glob(filename + '.*'))
您可以使用:

您可以使用:


。是否要返回
True
以防万一
L1.zip
存在,或任何以L1开头的文件,例如
L1.txt
?@Mureinik任何文件都可以,谢谢。。是否要返回
True
以防万一
L1.zip
存在,或任何以L1开头的文件,例如。,
L1.txt
?@Mureinik任何文件都可以,谢谢。您的示例中没有使用glob。@Daniel arg!忘记了最重要的部分!已编辑并修复,感谢您的注意。您的示例中没有使用glob。@Daniel arg!忘记了最重要的部分!编辑并修复,感谢您的注意。我的搜索参数实际上是一个相当长的ID。感谢您的解决方案;它还避免了另一个导入
glob
在不同情况下可能有用。我的搜索参数实际上是一个相当长的ID。感谢您的解决方案;它还避免了另一个导入<代码>全局在不同的情况下可能有用。