Python中的open+append无法按预期工作

3
根据文档,如果我使用open("file","a")并写入文件,则新数据将被追加,但在下面的示例中,第二个命令只会覆盖文件。我不太明白为什么。
import subprocess

startupinfo = subprocess.STARTUPINFO()
subprocess.STARTF_USESHOWWINDOW = 1
startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW

with open(r"c:\folder\test.txt","a") as log:
    Process = subprocess.Popen(['dir'],
                               stdout = log, stderr = log,
                               startupinfo = startupinfo,
                               shell=True)

with open(r"c:\folder\test.txt","a") as log:
    Process = subprocess.Popen(['dir'],
                               stdout = log, stderr = log,
                               startupinfo = startupinfo,
                               shell=True)

我已经尝试了“a+b”模式,但最终结果相同。
1个回答

4

subprocess 中文件位置不会增加。在第二个 with 语句中 log.tell() 返回 0。你可以将 log 的位置增加到文件的末尾。并且等待第一个 Process 看起来是好的。以下代码适用于我:

import subprocess
from os import linesep, stat 

with open(r"test.txt","a") as log:
    Process = subprocess.Popen(['dir'],
                               stdout = log, stderr = log,
                               shell=True)
    Process.wait()

with open(r"test.txt","a") as log:
# this prints 0
    print log.tell()
# get the length of the file log
    pos = stat(r"test.txt").st_size
    print pos
# go to the end of log
    log.seek(pos)
    Process = subprocess.Popen(['dir'],
                               stdout = log, stderr = log,
                               shell=True)

2
“log.seek(0, io.SEEK_END)”(带有“import io”)不比使用“stat”更优雅吗?或者由于某些原因在这里无法使用? - Jonas Schäfer
我想你是对的。我不知道seek()函数有第二个可选参数。 - Holger
太好了!抱歉我忘记了等待。实际上代码更复杂,我只是发布了最小必要的内容以展示我的意思。只是出于好奇,这不算是一个bug吗?我的意思是,如果我将其作为“a”打开,它不应该位于文件末尾吗? - Mac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接