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

标签 python io file-handling

我使用下面的代码读入一个文本文件(总是几千行)。 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)

关于python - 什么情况下python的f.readlines方法会失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554332/

相关文章:

java - C 中的按位运算符 ~=

从随机访问文件读取对象时 C++ 程序崩溃

python - 如何在我自己的类方法中使用 `with open`?

c - 在C中对文本文件中的数据进行排序

python - 为什么要创建第二个图而不是填充第二个子图?

javascript - 如何在 Django 博客中添加社交分享按钮

mysql - Zen Cart 对数据库的写入过多。可能的解决方案?

python - Pandas 在 groupby 中设置值

python - OpenCV - 使用 VideoWriter 不提供文件

从文件夹/ja​​r 文件读取资源时用于抽象 I/O 的 Java 库?