一次读取整个文件

时间:2011-10-24 16:34:36

标签: python file

我试图编写一个获取路径的函数并返回此文件的内容。无需错误处理。我提出了以下

def read_all_1(path):
    f = open(path)
    s = f.read()
    f.close()
    return s

def read_all_2(path):
    with open(path) as f:
        return f.read()

我的问题:

  • 哪一个被认为是pythonic?
  • 在第二个功能中,文件将通过""自动关闭?
  • 有更好的方法,也许有一些内置函数?

2 个答案:

答案 0 :(得分:9)

它们都非常pythonic。要解决第二个问题,在第二个函数中,文件确实会自动关闭。这是与with语句一起使用的协议的一部分。具有讽刺意味的是,文件保证在您的第一个示例中关闭(更多关于为什么在一秒钟内)。

最终,根据PEP 343,我会选择使用with语句,这就是原因:

with EXPR as VAR:
    BLOCK

翻译成:

mgr = (EXPR)
exit = type(mgr).__exit__  # Not calling it yet
value = type(mgr).__enter__(mgr)
exc = True
try:
    try:
        VAR = value  # Only if "as VAR" is present
        BLOCK
    except:
        # The exceptional case is handled here
        exc = False
        if not exit(mgr, *sys.exc_info()):
            raise
        # The exception is swallowed if exit() returns true
finally:
    # The normal and non-local-goto cases are handled here
    if exc:
        exit(mgr, None, None, None)

正如您所看到的,在这种情况下您会得到很多保护 - 无论干预代码中发生什么,您的文件都会被保证关闭。这也有助于提高可读性;想象一下,如果每次打开文件时都必须放置这么大的代码块,那么就可以了。

答案 1 :(得分:3)

我会说第二个,是的,文件将被关闭,想到这样的with语句:

try:
   f = open(filepath)
   <code>
finally:
   f.close()

关于你的第三个问题,没有其他方法不涉及打开文件。


第三种方式可以是(没有明确关闭文件):

open(filepath).read()

当文件对象被垃圾收集时,文件将被关闭,但IMHO显式优于隐式文件。