Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python open+append not working as expected

According to the documentation if I use open("file","a") and write to the file the new data would be appended, but in the example below the second command just overwrites the file. I don't quite get why.

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)

I already tried mode "a+b", but I get the same end result.

like image 280
Mac Avatar asked May 31 '26 18:05

Mac


1 Answers

Within the subprocess the file position is not increased. log.tell() returns 0 in the second with statement. You can incease the position of log to the end of the file. And it seems to be good to wait() for the first Process. Following works for me:

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)
like image 77
Holger Avatar answered Jun 03 '26 09:06

Holger