我正在尝试编写一个函数,该函数获取路径并返回该文件的内容。无需进行错误处理。我想出了以下代码:
def read_all_1(path):
f = open(path)
s = f.read()
f.close()
return s
def read_all_2(path):
with open(path) as f:
return f.read()
我的问题:
- 哪一个被认为更符合Python的风格?
- 在第二个函数中,文件是否会通过“with”自动关闭?
- 是否有更好的方法,也许是一些内置函数?
do_something_with(read_all(path) + something_else)
。 - georgdo_something_with(open('the_file.txt').read())
,这将会被很好地"垃圾回收"。 - heltonbiker