一次读取整个文件

geo*_*org 4 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()
Run Code Online (Sandbox Code Playgroud)

我的问题:

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

Nat*_*ate 9

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

最终,我会选择使用该with声明,这就是为什么 - 根据PEP 343:

with EXPR as VAR:
    BLOCK
Run Code Online (Sandbox Code Playgroud)

被翻译成:

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)
Run Code Online (Sandbox Code Playgroud)

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