0

So I'm learning about reading and writing from file in python. I seem to understand that if you use 'w' in order to open an existing file for writing, it will overwrite that file. So right now, I am doing something like this:

with open('something.json', 'r') as open_file:
    get some stuff

with open('something.json', 'w') as open_file:
    add some stuff

Is it normal to open and close the file twice in order to both read and write, or is there an optional argument that might allow me to do everything all at once?

rocksNwaves
  • 5,331
  • 4
  • 38
  • 77
  • First of all, to add some stuff you need to use `'a'`, cause `'w'` will rewrite file. And yes, it's ok to do like this. – Olvin Roght Sep 10 '19 at 22:37
  • 2
    You might be looking for [`'r+'`](https://stackoverflow.com/a/1466036/6275103). – DjaouadNM Sep 10 '19 at 22:41
  • Do you want to save any of the original file? Another option, especially when learning is write to a different file name. That way you preserve the original for further testing. – hpaulj Sep 10 '19 at 23:14

2 Answers2

4

It depends on what you need to do. If you need to read and write it is better to do everything with a single with statement. In this way you are not doing extra work to reopen the file (e.g loading the file descriptor in memory).

There are different options depending on what you need to do for the with open statement:

  • r+ Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ Open for reading and appending (writing at end of file). The initial file position for reading is at the beginning of the file, but output is appended to the end of the file (but in some Unix systems regardless of the current seek position).

Nikaido
  • 4,443
  • 5
  • 30
  • 47
  • by stream, do you mean the location in the file where new data is added? And does 'r+' overwrite the file in question like 'w' does? – rocksNwaves Sep 10 '19 at 22:47
  • 2
    @rocksNwaves: `'r+'` leaves the existing file data in place (until you write new data to replace it), it doesn't truncate on open like `'w'`. If you write wholly new data later, you can call `.truncate()` when you're done to ensure old data isn't leftover past the new data you wrote. – ShadowRanger Sep 10 '19 at 22:49
1

Your approach is pythonic and I would consider it a good practice.

Consider something like the following

with open('something.json', 'r+') as open_file:
  data =  open_file.read()
  ... computation with the data ...
  output = ...
  open_file.write(output)
bearrito
  • 2,217
  • 1
  • 25
  • 36