I use files a lot in my program and sometimes I open them only once to use as an argument, like this:
data = json.load(open("data.json", 'r'))
Do I have to open it first, then use it as an argument and close? Does Python close it automatically in that case?
(I'm using Python 3.7)
Asked
Active
Viewed 287 times
0

tiesto228
- 25
- 3
-
If you don't explicitly close it, it will remain open until the process exits, which you generally want to avoid since it consumes system resources. You can also embed your call in a `with open(...) as fh:` if you prefer, in which case it is implicitly closed at the end of the `with` statement. – Tom Karzes Feb 02 '20 at 09:51
1 Answers
2
You don't have to close the file, but it my result in unexpected behavior and/or memory leak if the program continues. Python provides the with statement to close it automatically
with open("data.json", 'r') as f:
data = json.load(f)

Guy
- 46,488
- 10
- 44
- 88