Python open+;追加未按预期工作

Python open+;追加未按预期工作,python,subprocess,Python,Subprocess,根据文档,如果我使用open(“file”,“a”)并将新数据写入文件,则会附加新数据,但在下面的示例中,第二个命令只会覆盖文件。我不太明白为什么 import subprocess startupinfo = subprocess.STARTUPINFO() subprocess.STARTF_USESHOWWINDOW = 1 startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW with open(r"c:\folder\test.

根据文档,如果我使用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”,但得到了相同的最终结果。

子流程中,文件位置没有增加
log.tell()
在第二条
with
语句中返回
0
。您可以将
log
的位置增加到文件的末尾。对于第一个
过程
等待()
似乎很好。以下是我的作品:

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)

使用
log.seek(0,io.seek_END)
(使用
import io
)不会比使用
stat
更优雅吗?或者是因为某种原因,这在这里不起作用吗?我想你是对的。我不知道
seek()
的第二个可选参数。太好了!对不起,我忘了等待。代码实际上更复杂,我只是发布了显示我的意思所需的最小值。只是出于好奇,这不是一种虫子吗?我的意思是,如果我把它作为“a”打开,它应该在文件的末尾,不是吗?