Python 如何检查文件是否存在,如果存在,如何创建文件';缺少,但文件路径不完整,如下所示

Python 如何检查文件是否存在,如果存在,如何创建文件';缺少,但文件路径不完整,如下所示,python,glob,Python,Glob,我必须在此路径下创建一个名为file.txt的空文本文件 /home/project/test*/today/file.txt 测试*每次都会更改,如测试产品或测试1等 我尝试了以下代码: if(os.path.exists("/home/project/test*/today/file.txt"): print "Found" else: open("/home/project/test*/today/file.txt",a).close()``

我必须在此路径下创建一个名为
file.txt
的空文本文件

/home/project/test*/today/file.txt

测试*每次都会更改,如测试产品或测试1等

我尝试了以下代码:

    if(os.path.exists("/home/project/test*/today/file.txt"):
        print "Found"
    else:
        open("/home/project/test*/today/file.txt",a).close()```
我犯了这个错误

        ```IOError: [Errno 2] No such file or directory: '/home/project/test*/today/file.txt'```

我知道我可以使用glob来搜索路径为*的文件,但我不知道如何在路径中有*的情况下创建文件。

您的代码在逻辑上没有任何意义。你基本上是说

if the file exists: display the text Found
otherwise the file does not exist, so try to open the file that does not exist

我会告诉你为什么它不起作用<代码>操作系统模块不支持通配符

如果您想使用通配符
*
,您可以使用glob

导入全局
导入操作系统
从pathlib导入路径
def check_查找_文件(文件路径):
对于glob.glob(filepath)中的filepath_对象:
如果os.path.isfile(filepath\u对象):
返回真值
返回错误
file_to_check=“/home/project/test*/today/file.txt”
如果没有(检查\u文件(文件\u到\u检查):
路径(文件到检查).touch()

您的代码在语法上不正确。我甚至不知道解释器会如何理解。您需要理解
*
将是什么,因为
打开()
call不会为您这样做。如果任何与
test*
匹配的目录中都不存在任何文件,您希望在其中哪一个目录中创建新文件?每次*都会更改,因此我将其保留为。*让我问您一个问题@tim91,假设您在/home/project/test1、/home/project/test2…/home/project/tes中有文件夹tn.你会在每一个文件中对一个文件进行编码吗?你的问题在逻辑上是不正确的。他已经说过他没有使用通配符。他的意思是,文件名是任意的。:(只是一个措辞糟糕的问题。