对于yaml加载使用open vs with

时间:2016-01-20 21:11:45

标签: python

我有一个程序可以读取yaml配置,只读。我想知道以下哪一个更像Pythonic

try:
    config = yaml.load(open(filepath))
except Exception as error:
    print error

vs使用with语句

try:
    with open(filepath) as f:
        config = yaml.load(f)
except Exception as error:
    print error

我更喜欢第一个,因为它更容易阅读,因为没有写我不认为文件关闭优雅的问题。想法?

1 个答案:

答案 0 :(得分:0)

使用第二个。来自文档:

  

最好在处理文件时使用with关键字   对象。这样做的好处是文件在之后正确关闭   它的套件即使在路上引发异常也会完成。