繁体   English   中英

仅当文件已存在时才附加到文件

[英]Append to file only if it already exists

在我的脚本开始时,文件script.log应该存在并且消息被附加到它。 但是如果该文件不存在(用户已决定删除该文件),则不应再次创建该文件,而是将消息打印到stdout 仅当您看到它时才填充桶。

怎么做?
一定有很多人遇到过类似的问题,但我找不到任何解决方案。


我的目标类似于以下代码,但是当找不到文件时,追加模式不会触发任何异常:

if os.path.exists('script.log'):
    with open('script.log', 'a') as f:
        f.write('foo')
else:
    print('foo')

我知道以下代码应该可以工作,但理想情况下我想避免它,因为它包含竞争条件

 if os.path.exists('script.log'): with open('script.log', 'a') as f: f.write('foo') else: print('foo')

单独使用os.openos.fdopen而不是open

open使用的"a"模式尝试使用标志os.O_APPENDos.O_CREAT打开文件,如果文件不存在则创建文件。 我们将使用os.fdopen使用os.O_APPEND标志,如果它不存在,则会引发FileNotFoundError

假设它成功,我们将使用os.fdopenfdopen返回的fdopen在一个类似文件的对象中。 (不幸的是,这需要一个看似多余的"a"标志。)

import os
import sys

try:
    fd = os.open('script.log', os.O_APPEND)
    with os.fdopen(fd, "a") as f:
        f.write("foo")
except FileNotFoundError:
    print("foo")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM