如何检查文件是否存在,如果丢失,则创建一个文件,而文件路径如下所示不完整

问题描述 投票:0回答:3

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

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

test *每次都会更改,例如test_product或test_1等。

我尝试了以下代码,有人可以帮我这个忙。

    if(os.path.exists("/home/project/test*/today/file.txt"):
        print "Found"
    else:
        open("/home/project/test*/today/file.txt").close()```

我收到此错误

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

我知道我可以使用glob搜索带有*之类的路径的文件,但是我无法弄清楚在路径中带有*的情况下如何创建文件。

我必须在此路径/home/project/test*/today/file.txt下创建一个名为file.txt的空文本文件。test *每次都会更改,例如test_product或test_1等。我尝试了以下代码,可以。 ..

python glob
3个回答
0
投票

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


0
投票

我会告诉你为什么它不起作用。 os模块不支持通配符。


-1
投票

尝试使用“ w”:写入模式,只需将其作为第二个arg添加到open方法中

© www.soinside.com 2019 - 2024. All rights reserved.