python f.readlines 方法在什么情况下会失效?

Under which circumstances will the python f.readlines method fail?

我使用下面的代码读入一个文本文件(总是几千行)。 except Exception as e 块是不必要的吗?

try:
        in_file=open(in_file,'rU')
        try:
            in_content=in_file.readlines()
        except Exception as e:
            sys.stderr.write('Error: %s\n' % e.message)
            sys.exit(1)
        finally:
            in_file.close()
except IOError:
        sys.stderr.write('I/O Error: Input file not found.')
        sys.exit(1)

另外请问Python中的file.readlines()方法在什么情况下会失效?

我相信 IOError 是唯一可能发生的事情。这包括文件不存在和权限不足。我所看到的任何 python 参考文献都只有 IOError 文件:)。我不确定堆栈跟踪是什么意思,因为它似乎只是打印错误本身?

import sys
try:
    with open("in_file",'rU') as in_file:
        in_content=in_file.readlines()
except Exception as e: #Should be replaceable with IOError, doesn't hurt to not 
    sys.stderr.write('%s\n' % e)
    sys.exit(1)

读取文件的 pythonic 方式如下所示:

with open(in_file_name,'rU') as in_file:
    in_content = in_file.readlines()

这应该会给您代码带来的所有好处。所以您不必担心会发生什么样的错误。 Python 会处理的。使用 with 语句打开的文件将在出现异常时关闭。