Python open() r+ argument


#1
with open("text.txt", "r+") as my_file:
  my_file.write("Success")
  print my_file.read()
  

For some reason, the print my_file.read() line won’t print anything. It will write, “Success” in the file, and the read() method won’t cause an error, but it just won’t actually read the file because it prints nothing to the console. Does anyone know a solution for this?


#2

In thruth, the program is reading your file, just not the line you just wrote. It is reading the next line after that, if I’ve got my bearings correct. If you let the file close, then re-open it you can read it.

with open('text.txt', 'r+') as my_file:
  my_file.write('Success!\n')
  my_file.write('Bravo!\n')
  print (my_file.read())

# <-  blank line prints

with open('text.txt', 'r+') as my_file:
  print (my_file.read())
  my_file.write('Hear, hear!\n')
 
# <-  Success!
# <-  Bravo!
# followed by a blank line

with open('text.txt', 'r+') as my_file:
  print (my_file.read())
  my_file.write('Good Job!\n')

# <-  Success! 
# <-  Bravo!
# <-  Hear, hear!
# followed by a blank line

with open('text.txt', 'r+') as my_file:
  print (my_file.read())

# <-  Success!
# <-  Bravo!
# <-  Hear, hear!
# <-  Good Job!

#3

In most cases the right thing to do is to read the whole file, modify it, and write it all out again

You’d only need to mix read and write if the file is large or if you’re really looking to get surgical about it, but you better know what you’re doing and you better be able to motivate the added potential for getting it wrong

For small files there might not be a measurable difference, especially if the os doesn’t have it in memory and hardware has to go and read it (incredibly slow)


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.