首页 > 解决方案 > os.path.exists 导致文件被删除

问题描述

在为 python 使用Audacity脚本环境时,我遇到了以下问题。它创建一个临时文件,可以在其中编写要由 Audacity 执行的命令。Audacity 启动时正在创建两个相关文件。

我的脚本包含以下片段(原始来源):

# Initialize variable depending on os:
if sys.platform == 'win32':
    print("pipe-test.py, running on windows")
    TONAME = '\\\\.\\pipe\\ToSrvPipe'
    FROMNAME = '\\\\.\\pipe\\FromSrvPipe'

# Check if temp files actually exist
if not os.path.exists(TONAME):
    print(" ..does not exist.  Ensure Audacity is running with mod-script-pipe.")
    sys.exit()

到目前为止一切都很好,找到了文件。然后我尝试打开,每次都操作失败。我在这里和那里做了一些调整,但最终发现这种奇怪的行为表明打开文件不是问题,而是exists()检查。我像这样更改了我的代码:

# Initialize variable depending on os:
[...]

# Check if temp files actually exist (it exists)
if not os.path.exists(TONAME):
    print(" ..does not exist.  Ensure Audacity is running with mod-script-pipe.")
    sys.exit()

# Check if temp files actually exist (it is gone)
if not os.path.exists(TONAME):
    print("File is gone now")
    sys.exit()

第二次检查会告诉我,在我检查文件是否存在后,该文件突然消失了。这怎么可能?怎么可能os.path.exists()删除了我的临时文件?

标签: python

解决方案


推荐阅读