Reputation: 6164
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?
Upvotes: 1
Views: 1635
Reputation: 2315
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)
Upvotes: 1
Reputation: 4629
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).
Upvotes: 4