Search code examples
pythoncontextmanager

One-line syntax to read and return file on Python using with


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.


Solution

  • 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