简体   繁体   English

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

[英]Append to file only if it already exists

At the start of my script, the file script.log is expected to exist and messages are being appended to it.在我的脚本开始时,文件script.log应该存在并且消息被附加到它。 But if the file does not exist (the user has decided to delete the file), the file should not be created again, the messages will be printed to stdout instead.但是如果该文件不存在(用户已决定删除该文件),则不应再次创建该文件,而是将消息打印到stdout Fill the bucket only if you see it.仅当您看到它时才填充桶。

How to do that?怎么做?
Loads of people must have had a similar problem but I couldn't find any solution.一定有很多人遇到过类似的问题,但我找不到任何解决方案。


I aimed at something like the following code but the append mode does not trigger any exception when the file is not found: 我的目标类似于以下代码,但是当找不到文件时,追加模式不会触发任何异常:

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

I know that the following code should work but ideally I would like to avoid it because it contains a race condition :我知道以下代码应该可以工作,但理想情况下我想避免它,因为它包含竞争条件

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

Use os.open and os.fdopen separately rather than open .单独使用os.openos.fdopen而不是open

The "a" mode used by open tries to open the file using the flags os.O_APPEND and os.O_CREAT , creating the file if it doesn't already exist. open使用的"a"模式尝试使用标志os.O_APPENDos.O_CREAT打开文件,如果文件不存在则创建文件。 We'll use os.fdopen to use just the os.O_APPEND flag, causing a FileNotFoundError to be raised if it doesn't already exist.我们将使用os.fdopen使用os.O_APPEND标志,如果它不存在,则会引发FileNotFoundError

Assuming it succeeds, we'll use os.fdopen to wrap the file descriptor returned by fdopen in a file-like object.假设它成功,我们将使用os.fdopenfdopen返回的fdopen在一个类似文件的对象中。 (This requires, unfortunately, a seemingly redundant "a" flag.) (不幸的是,这需要一个看似多余的"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