Skip to main content
 首页 » 编程设计

python之什么情况下python的f.readlines方法会失败

2025年05月04日13leader

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

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)