在哪种情况下python f.readlines方法会失败?

时间:2016-01-01 07:18:54

标签: python io file-handling

我使用下面的代码读取文本文件(总是几千行)。是否不需要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()方法失败的情况?

2 个答案:

答案 0 :(得分:1)

我相信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)

答案 1 :(得分:0)

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

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

这应该可以为您提供代码的所有好处。因此,您无需担心会发生什么样的错误。 Python将负责它。如果出现异常,将使用with语句打开的文件将被关闭。

相关问题