gpt4 book ai didi

python - 在 python 中使用异常和文件时清理

转载 作者:太空宇宙 更新时间:2023-11-03 12:52:26 26 4
gpt4 key购买 nike

我现在正在学习 python 几天,并且正在为它的“精神”而苦苦挣扎。我来自 C/C++/Java/Perl 学校,我知道 python 不是 C(根本),这就是为什么我试图理解精神以充分利用它(到目前为止很难) ...

我的问题特别关注异常处理和清理:这篇文章末尾的代码旨在模拟一个相当常见的文件打开/解析情况,您需要在出现错误的情况下关闭文件...

我见过的大多数示例都使用 try 语句的“else”子句来关闭文件……这对我来说很有意义,直到我意识到错误可能是由于

  • 开口本身(在这种情况下没有必要关闭not打开的文件)
  • 解析(其中如果文件需要关闭)

这里的陷阱是,如果您使用 try block 的“else”子句,那么如果在解析过程中发生错误,文件将永远不会关闭!另一方面,使用“finally”子句会导致额外的必要检查,因为如果在打开期间发生错误,则 file_desc 变量可能不存在(请参阅下面代码中的注释)...

这个额外的检查是低效的,而且充满了狗屎,因为任何合理的程序都可能包含数百个符号,并且解析 dir() 的结果是一件很痛苦的事情……更不用说这样的语句缺乏可读性了。 ..

大多数其他语言都允许变量定义,这可以节省时间...但在 python 中,一切似乎都是隐式的...

通常,一个人会声明一个 file_desc 变量,然后为每个任务使用许多 try/catch block ...一个用于打开,一个用于解析,最后一个用于关闭()...不需要嵌套它们...在这里我不知道声明变量的方法...所以我被困在问题的开头!

那么这里的 python 精神是什么???

  • 用两种不同的方法拆分开/解析?怎么样?
  • 使用某种嵌套的 try/except 子句 ???怎么样?
  • 也许有一种方法可以声明 file_desc 变量,然后就不需要额外的检查了……这有可能吗???理想的???
  • close() 语句呢???如果它引发错误怎么办?

感谢您的提示...这是示例代码:

class FormatError(Exception):
def __init__(self, message):
self.strerror = message
def __str__(self):
return repr(message)


file_name = raw_input("Input a filename please: ")
try:
file_desc = open(file_name, 'r')
# read the file...
while True:
current_line = file_desc.readline()
if not current_line: break
print current_line.rstrip("\n")
# lets simulate some parsing error...
raise FormatError("oops... the file format is wrong...")
except FormatError as format_error:
print "The file {0} is invalid: {1}".format(file_name, format_error.strerror)
except IOError as io_error:
print "The file {0} could not be read: {1}".format(file_name, io_error.strerror)
else:
file_desc.close()
# finally:
# if 'file_desc' in dir() and not file_desc.closed:
# file_desc.close()

if 'file_desc' in dir():
print "The file exists and closed={0}".format(file_desc.closed)
else:
print "The file has never been defined..."

最佳答案

处理这个问题的最简单方法是使用 Python 2.5+ 中的文件对象是 context managers 的事实。 .您可以使用 with进入上下文的语句;上下文管理器的 __exit__ 方法在退出此 with 范围时自动调用。然后文件对象的上下文管理自动关闭文件。

try:
with file("hello.txt") as input_file:
for line in input_file:
if "hello" not in line:
raise ValueError("Every line must contain 'hello'!")
except IOError:
print "Damnit, couldn't open the file."
except:
raise
else:
print "Everything went fine!"

打开的 hello.txt 句柄将自动关闭,with 范围内的异常会传播到外部。

关于python - 在 python 中使用异常和文件时清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1149983/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com