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”,但我得到了相同的最终结果。

4

1 回答 1

4

文件内的subprocess位置不增加。在第二个语句中log.tell()返回。您可以将 的位置增加到文件的末尾。第一个似乎很好。以下对我有用:0withlogwait()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)
于 2012-12-11T14:19:15.667 回答