-
-
Notifications
You must be signed in to change notification settings - Fork 32.2k
gh-132631: Fix "I/O operation on closed file" when parsing JSON Lines file #132632
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
@@ -55,7 +55,7 @@ def main(): | |||
infile = open(options.infile, encoding='utf-8') | |||
try: | |||
if options.json_lines: | |||
objs = (json.loads(line) for line in infile) | |||
objs = tuple(json.loads(line) for line in infile) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This has significant memory implications for large .jsonl
files. It might be better to instead move the finally
clause either to the outer try
or just after the with outfile
block, but that does have implications for the infile == outfile
case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, yeah, moving it gives a blank file when infile == outfile
...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Or we could load all the lines into a list. This uses more memory than before, but less than the tuple as we're only deserialising each line when consumed from the generator:
objs = tuple(json.loads(line) for line in infile) | |
lines = infile.readlines() | |
objs = (json.loads(line) for line in lines) |
I don't think it's worth adding much extra complexity for this CLI, as if someone needs to process extremely large .jsonl
files they can write their own code to do exactly what they need.
Co-authored-by: Brian Schubert <brianm.schubert@gmail.com>
Before
After