2024-04-25 19:18:26 发布
网友
我是Python新手,现在正在学习this关于文件处理的教程。你知道吗
如果向下滚动,您可以看到如何使用Python关闭文件并且在它下面他正在使用try和finally, 我的问题是,在我的程序中,我得到一个错误:'f'没有定义。你知道吗
try
finally
为什么我会遇到这个问题?我错过什么了吗?你知道吗
示例:
try: f = open("test.txt",encoding = 'utf-8') finally: f.close()
我也不想从一本好书开始。你知道吗
您可能遇到的错误是Name 'f' can be not defined,因为如果在open方法期间出现错误,您将永远不会分配f,因此它不会在finally中定义。一种解决方案是在以下情况之前分配另一个值:
Name 'f' can be not defined
open
f
f = None try: f = open("test.txt", encoding='utf-8') except FileNotFoundError as fnfe: print("File not found") exit(10) finally: if f: f.close()
但是由于这种语法不是很好,您可以使用with语句,当您离开块时,它会自动关闭对象,但是一定要捕获FileNotFoundError
with
FileNotFoundError
try: with open("test.txt",encoding = 'utf-8') as f: # perform file operations except FileNotFoundError as fnfe: print("File not found")
最好使用以下语法:
with open("test.txt", encoding = 'utf-8') as f: # Do something with f
不需要关闭它,with为您完成。你知道吗
您可能遇到的错误是
Name 'f' can be not defined
,因为如果在open
方法期间出现错误,您将永远不会分配f
,因此它不会在finally
中定义。一种解决方案是在以下情况之前分配另一个值:但是由于这种语法不是很好,您可以使用
with
语句,当您离开块时,它会自动关闭对象,但是一定要捕获FileNotFoundError
最好使用以下语法:
不需要关闭它,
with
为您完成。你知道吗相关问题 更多 >
编程相关推荐