1

Using Python I'm loading JSON from a text file and converting it into a dictionary. I thought of two approaches and wanted to know which would be better.

Originally I open the text file, load the JSON, and then close text file.

import json

// Open file. Load as JSON.
data_file = open(file="fighter_data.txt", mode="r")
fighter_match_data = json.load(data_file)
data_file.close()

Could I instead do the following instead?

import json

// Open file. Load as JSON.
fighter_match_data = json.load(open(file="fighter_data.txt", mode="r"))

Would I still need to close the file? If so, how? If not, does Python close the file automatically?

Zakar H.
  • 25
  • 6

2 Answers2

3

Personally wouldn't do either. Best practice for opening files generally is to use with.

with open(file="fighter_data.txt", mode="r") as data_file:
    fighter_match_data = json.load(data_file)

That way it automatically closes when you're out of the with statement. It's shorter than the first, and if it throws an error (say, there's an error parsing the json), it'll still close it.


Regarding your actual question, on needing to close the file in your one liner.

From what I understand about file handling and garbage collection, if you're using CPython, since the file isn't referenced anymore it "should" be closed straight away by the garbage collector. However, relying on garbage collection to do your work for you is never the nicest way of writing code. (See the answers to open read and close a file in 1 line of code for information as to why).

SCB
  • 5,821
  • 1
  • 34
  • 43
  • Thank you for the response. This helps me understand why the code works in that way and clears up my assumptions. I'll use your approach. – Zakar H. Mar 08 '18 at 06:17
0

Your code as under is valid:

fighter_match_data = json.load(open(file="fighter_data.txt", mode="r"))

Consider this part:

open(file="fighter_data.txt", mode="r") .  #1

v/s

data_file  = open(file="fighter_data.txt", mode="r") .  #2

In case of #2, in case you do not explicitly close the file, the file will automatically be closed when the variable ceases to exist[In better words, no reference exists to that variable] (when you move out of the function).

In case of #1, since you never create a variable, the lifespan of that implicit variable created for opening that file ceases to exist on that line itself. And python automatically closes the file after opening it.

Vishal
  • 3,178
  • 2
  • 34
  • 47