我正在学习Python,发现有两种文件打开操作。 第一种是:
myreadfile = open("bear.txt", "r")
content = myreadfile.read()
第二种方法是
with open("bear.txt") as file:
content = file.read()
我想知道这两种方法之间是否有差异,哪一种更适合使用。
我正在学习Python,发现有两种文件打开操作。 第一种是:
myreadfile = open("bear.txt", "r")
content = myreadfile.read()
第二种方法是
with open("bear.txt") as file:
content = file.read()
我想知道这两种方法之间是否有差异,哪一种更适合使用。
with
方法是一种上下文管理器,如果您用它来读写I/O文件,它会自动关闭文件,不需要添加一行file.close()
,如文档中所述:
上下文管理器允许您在需要时精确地分配和释放资源。 上下文管理器的最常用示例是
with
语句。 假设您有两个相关操作,希望作为一对执行,并在其中间添加一段代码块。 上下文管理器允许您做到这一点。
文档中有一个普通的with
语句的例子:
with open('some_file', 'w') as opened_file:
opened_file.write('Hola!')
等同于:
file = open('some_file', 'w')
try:
file.write('Hola!')
finally:
file.close()
它说:
与第一个示例相比,仅使用
with
就消除了大量样板代码。使用with
语句的主要优点是,它确保文件关闭,而不需要注意嵌套块如何退出。
正如文档中所提到的那样,上下文管理器可以使用 class
实现:
至少,上下文管理器定义了
__enter__
和__exit__
方法。
如上所示,在 class
中实现上下文管理器的示例可能是:
class File(object):
def __init__(self, file_name, method):
self.file_obj = open(file_name, method)
def __enter__(self):
return self.file_obj
def __exit__(self, type, value, traceback):
self.file_obj.close()
with File('demo.txt', 'w') as opened_file:
opened_file.write('Hola!')
由于魔术方法__enter__
和__exit__
,代码可以像上下文管理器一样运行。
第一个不会自动关闭文件,而第二个会。
with
语法被称为上下文,一旦退出上下文,它将自动关闭文件,以及在操作期间出现问题时也会关闭文件。with
块时被调用:在离开时,它会关闭。这比另一种方法更好,甚至更优秀。myreadfile = open("bear.txt", "r")
content = myreadfile.read()
myreadfile.close()
因为当read()
抛出异常时,close()
行没有被执行。
这更像是
myreadfile = open("bear.txt", "r")
try:
content = myreadfile.read()
finally:
myreadfile.close()
但更易于使用。