r/pythonhelp • • Dec 13 '19

Help me please! I’m trying to modify files, but when i run it, it wipes the file clean??

Post image
3 Upvotes

4 comments sorted by

2

u/maedox Dec 13 '19

You cannot read and write to the same file like that.

Either

  1. read all lines first, then write them back

  2. 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.

1

u/blendedTime Dec 14 '19

Thank you!! I’ll try that

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.

  1. You may need to write the entire file, line by line, and then do the 'replace' only in the one applicable spot.

  2. 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.