Python开放追加无法正常工作

根据文档,如果我使用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.您可以将日志的位置增加到文件末尾.并且,等待第一个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)
上一篇:Python子进程.Popen PIPE和SIGPIPE


下一篇:如何将带有空格的字符串从Python发送到Bash子进程作为单个值?