r/pythonhelp • u/blendedTime • Dec 13 '19
Help me please! I’m trying to modify files, but when i run it, it wipes the file clean??
3
Upvotes
3
u/someoneonboard1 Dec 13 '19
Your reading and writing is the same filename. Try making a different filename for writing. And then rename it after editing it. You can then delete the original filename.
0
u/scoobybejesus Dec 13 '19
I don't know for sure, but I have two thoughts.
You may need to write the entire file, line by line, and then do the 'replace' only in the one applicable spot.
You may need to iterate on (idx, line), possibly with enumerate(), and match on the index.
I don't know this language - just wanted to tell you what I've seen in my experience with other languages.
2
u/maedox Dec 13 '19
You cannot read and write to the same file like that.
Either
read all lines first, then write them back
read line by line and write to a temporary file, then rename the temporary file.
The first approach works well for small files, the second approach if done right can handle any file size.