-2

I need to read a file and return result: this is the syntax I use

return json.loads(with open(file, 'r') as f: f.read())

I know that we cannot write with open in one line, so I look for the correct syntax to fix that.

tripleee
  • 175,061
  • 34
  • 275
  • 318
HISI
  • 4,557
  • 4
  • 35
  • 51
  • 2
    Note `with` is a *context manager*, not a loop: https://docs.python.org/3/reference/compound_stmts.html#the-with-statement. It's also not really about having it on one line, so much trying to use a statement as an argument to a function. – jonrsharpe Jan 07 '20 at 12:16

1 Answers1

3

The requirement to do this in a single line is dubious, but you can easily fix the syntax:

with open(file, 'r') as f: return json.loads(f.read())

Having json read the file for you is probably both more idiomatic and more elegant:

with open(file, 'r') as f: return json.load(f)

Python allows you to write a "suite" of statements after the colon to create a block in a single line. Anything which looks like

whatever in a block: do things; more stuff

is equivalent to the multi-line

whatever in a block:
  do things
  more stuff
tripleee
  • 175,061
  • 34
  • 275
  • 318