-3

I want to open a file, load the content, and then write new content into this file to overwrite everything in the file. I tested but it didn't work as expected:

handler = open('test.txt', 'w+')

for line in handler:
    print(line)

It prints out nothing. It seems 'w+' wipes output everything in the first place, but according to documentation:

Write and Read (‘w+’) : Open the file for reading and writing. For an existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.

What's the issue?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • 2
    "For an existing file, data is truncated and over-written" – puncher Aug 05 '22 at 22:51
  • Then what does this mean: 'for reading and writing'? To read from where? What's the correct mode for my purpose? – marlon Aug 05 '22 at 22:52
  • 1
    Use `r+` for reading and writing with no truncation – Iain Shelvington Aug 05 '22 at 22:55
  • 1
    Does this answer your question? [Why does changing to \`w+\` mode for simultaneous reading from and writing to a file cause the read to fail?](https://stackoverflow.com/questions/61655129/why-does-changing-to-w-mode-for-simultaneous-reading-from-and-writing-to-a-fi) (particularly the answer that says: "*This mode is meant to allow you to go back and read what you wrote after opening the file.*") – Gino Mempin Aug 05 '22 at 23:00
  • The diagram from this related post is useful for reading-and-writing confusions: [Difference between modes a, a+, w, w+, and r+ in built-in open function?](https://stackoverflow.com/q/1466000/2745495) – Gino Mempin Aug 05 '22 at 23:25

1 Answers1

-1

it clearly says in the documentation :

For an existing file, data is truncated and over-written

which means that the data will be deleted upon opening the file

the reading option here means

w+ opens for reading and writing, truncating the file but also allowing you to read back what's been written to the file

oubaydos
  • 194
  • 1
  • 13