Is there a way to open a file in both read and write?

Having gone through the whole lesson, I didn’t come across a way of opening a file in both ‘read’ and ‘write’ mode (I might have missed something). Is there such a way?

if you check the documentation:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files

you will see this mode exist. there is read ®, write (w), append (a) and read + write (r+)

16 Likes

Grand, thank you! I was on that page but clearly didn’t read it through…

Thank you, i saw it, but. I have this type of code:

with open("bad_bands.txt", "r+") as bad_bands_doc:
  bad_bands_doc.write("Grupa Tuberculyos")
  print(bad_bands_doc.read())

with open("bad_bands.txt") as bad_bands_doc:
  print(bad_bands_doc.read())

and it outputs:


Grupa Tuberculyos

There is an empty first line. I suppose that there should be a similar to the second line. But could you help me with why it is not?
Thank you.

ran the code on repl.it:

and went fine, maybe there was already content in the file? You could removing and creating the file again.

Is it fine though? Because what i would suppose is that there should be two identical lines of output:

Grupa Tuberculyos
Grupa Tuberculyos

Since we wrote “open("bad_bands.txt", "r+")” with "r+", i would expect we could write “bad_bands_doc.write("Grupa Tuberculyos")” to the file and then read it with “print” “print(bad_bands_doc.read())” so that we could output two identical lines.

I think the problem is with how python handles files.

here:

  bad_bands_doc.write("Grupa Tuberculyos")
  print(bad_bands_doc.read())

the write is kept in memory (to minimize interaction with disk, which is slow). So then when you use read(), there is nothing in the file yet

1 Like