Why does Python-2.7 on Windows truncate a file? The problem is well known with shutil.copyfile
but I don't understand how to avoid it when I'm changing the first line. File size is unknown and could be huge.
Reference below but I'd prefer better exception handling with something like the following code:
import os
import sys
import shutil
with open(sys.argv[1], 'r+') as src:
line = src.readline()
with open(sys.argv[1], 'r+') as dst:
dst.write = sys.argv[1]+'\n'
shutil.copyfileobj(src, dst)
Reference: change first line of a file in python
You need to create the new version of the file as a
NamedTemporaryFile
. After you finish constructing it, you then rename it on top of the old file.Code:
Test Code:
Before:
After: