使用 with 读取 Python 上的 return 文件的单行语法

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

我需要读取文件和return结果:这是我使用的语法

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

我知道我们不能在一行中写 with open,所以我寻找正确的语法来解决这个问题。

在一行中执行此操作的要求是可疑的,但您可以轻松修复语法:

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

json 为您阅读文件可能更地道也更优雅:

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

Python 允许您在冒号后写入 "suite" 语句以在一行中创建一个块。任何看起来像

的东西
whatever in a block: do things; more stuff

相当于多行

whatever in a block:
  do things
  more stuff