Skip to content

Commit 2d5e1bf

Browse files
committed
Use context managers for in and out
1 parent f72edc5 commit 2d5e1bf

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

Lib/json/tool.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -84,20 +84,23 @@ def main():
8484

8585
try:
8686
if options.infile == '-':
87-
infile = sys.stdin
87+
in_f = sys.stdin.fileno()
8888
else:
89-
infile = open(options.infile, encoding='utf-8')
90-
91-
if options.json_lines:
92-
objs = (json.loads(line) for line in infile)
93-
else:
94-
objs = (json.load(infile),)
89+
in_f = options.infile
9590

9691
if options.outfile is None:
97-
outfile = sys.stdout
92+
out_f = sys.stdout.fileno()
9893
else:
99-
outfile = open(options.outfile, 'w', encoding='utf-8')
100-
with outfile:
94+
out_f = options.outfile
95+
96+
with (open(in_f, 'r', encoding='utf-8') as infile,
97+
open(out_f, 'w', encoding='utf-8') as outfile):
98+
99+
if options.json_lines:
100+
objs = (json.loads(line) for line in infile)
101+
else:
102+
objs = [json.load(infile)]
103+
101104
if can_colorize(file=outfile):
102105
t = get_theme(tty_file=outfile).syntax
103106
for obj in objs:
@@ -108,8 +111,7 @@ def main():
108111
for obj in objs:
109112
json.dump(obj, outfile, **dump_args)
110113
outfile.write('\n')
111-
if infile is not sys.stdin:
112-
infile.close()
114+
113115
except ValueError as e:
114116
raise SystemExit(e)
115117

0 commit comments

Comments
 (0)