gpt4 book ai didi

Python open+append 没有按预期工作

转载 作者:太空宇宙 更新时间:2023-11-03 15:21:45 24 4
gpt4 key购买 nike

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

最佳答案

subprocess 中,文件位置没有增加。 log.tell() 在第二个 with 语句中返回 0。您可以将 log 的位置增加到文件末尾。对于第一个 Processwait() 似乎很好。以下对我有用:

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 open+append 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13821708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com