在python中关闭一个文件,用快捷方式打开

Zen*_*nce 0 python file-io

我刚开始使用带有lpthw的python并且有一个关闭文件的特定问题.

我可以打开一个文件:

input = open(from_file)
indata = input.read()

#Do something

indata.close()
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试将代码简化为一行:

indata = open(from_file).read()
Run Code Online (Sandbox Code Playgroud)

如何关闭我打开的文件,或者它已经自动关闭?

在此先感谢您的帮助!

Mic*_*yan 6

你只需要使用多行; 然而,更加pythonic的方式是:

with open(path_to_file, 'r') as f:
    contents = f.read()
Run Code Online (Sandbox Code Playgroud)

请注意,根据您之前的操作,如果抛出异常,您可能会错过关闭文件.这里的'with'语句将导致它被关闭,即使异常从'with'块传播出来.