【发布时间】:2018-09-24 21:19:54
【问题描述】:
我通常使用'with open',我不必担心再次关闭文件,但我想创建一个打开文件的函数:
def SafeOpen(filename,mode):
try:
infile=open(filename,mode)
except IOError as error:
print('Can not open file due to error:',str(error))
sys.exit(1)
return(infile)
我应该再次关闭文件吗?
编辑:
例如 - 我应该这样做:
infile=SafeOpen(filename,'r')
for line in infile:
print(line)
infile.close()
我可以改用“with open”吗?
【问题讨论】:
-
你的函数相当于
open函数,所以是的,你必须关闭文件。而且你应该让异常传播,因为在 python 中打开已经是安全的(因为未捕获的异常也会退出进程) -
您可以使用
with,因为您的函数返回了文件对象。上下文管理器是为文件对象创建的,python 不在乎它来自哪里。 -
with接受它所呈现的任何对象并调用其__enter__方法(如果没有这样的方法,则会引发错误)。open是一个类似于SafeOpen的函数,两者都使用__enter__方法返回一个文件对象(io.TextIOWrapper用于文本文件)。
标签: python python-3.x function file