I think you just want to open the file for writing without truncating it, which would be r+
. to make this reproducible, we first create a file that matches this format:
with open('many_lines.txt', 'w') as fd:
print('abcdefghi', file=fd)
for i in range(10000):
print(f'line {i:09}', file=fd)
then we basically do what you were doing, but with the correct mode:
with open('many_lines.txt', 'r+') as fd:
print('123456789', file=fd)
or you can use write
directly, with:
with open('many_lines.txt', 'r+') as fd:
fd.write('123456789')
Note: I'm opening in r+
so that you'll get an FileNotFoundError
if it doesn't exist (or the filename is misspelled) rather than just blindly creating a tiny file
The open
modes are directly copied from the C/POSIX API for the fopen
so your use of a
will trigger behaviour that says:
Subsequent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar