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+)

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

1 Like

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.

1 Like

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

3 Likes

It displays as expected when I used the .close function. According to the course we don’t need to use close() because using “with” automatically closes the file, however, I needed to explicitly close the file before I could read it.

with open(‘bad_bands.txt’, ‘r+’) as bad_bands_doc:
bad_bands_doc.write(‘I like all bands’)
bad_bands_doc.close()

with open(‘bad_bands.txt’, ‘r+’) as bad_bands_doc:
print(bad_bands_doc.read())

I’m unable to reproduce your issue on this lesson. It works fine without having to call .close(). What was your indentation here? See - How do I format code in my posts? for including proper formatting. Were those statements nested?