I have written a python script which read from a txt file and perform basic tasks like adding new line, deleting and editing existing lines. For deleting and editing, I load whole file as a list using "readlines()" and then overwrite file using edited list. This increases chance of data loss. So my question is, if I can edit txt files without overwriting them?
Asked
Active
Viewed 1,892 times
2
-
no, there is no way, in most filesystems, and in all the commonly used ones, to insert data" inside a file. – jsbueno Jan 15 '12 at 13:28
1 Answers
4
The traditional solution is to copy the original file to a .sav
file and then write the new edited version to the original filename:
>>> import os
>>> filename = 'somefile.txt'
>>> with open(filename) as f:
lines = f.readlines()
>>> basename, ext = os.path.splitext(filename)
>>> savefile = basename + '.sav'
>>> os.rename(filename, savefile)
>>> lines = map(str.upper, lines) # do your edits here
>>> with open(filename, 'w') as f:
f.writelines(lines)

Raymond Hettinger
- 216,523
- 63
- 388
- 485