python - 跳过文件的第一行时出错
问题描述
使用该命令next(a_file)
,我可以跳过文件的第一行,但前提是实际上有一行。如果在命令执行时文件中没有任何内容,我会收到错误消息。我怎样才能避免这个问题?
错误示例:
a_file = open("helloo.txt")
next(a_file)
print(a_file.read())
解决方案
只需使用一个try: except
块。您只想捕获StopIteration
异常,这样任何其他 ( FileNotFoundError
,...) 都不会在这里被捕获:
a_file = open("helloo.txt")
try:
next(a_file)
except StopIteration:
print("Empty file")
# or just
#pass
print(a_file.read())
推荐阅读
- sql - SQL:基于行值的动态连接
- python - 您将如何编写计算量较小的等价物 numpy.where(np.ones(shape))
- moodle - 如何使用 R/exams 在完形填空问题中添加子问题陈述
- javascript - 使用另一个数组对固定的对象数组进行排序
- vuetify.js - Vuetify 数据表标题自定义 - “隐藏默认标题”删除了排序功能
- youtube - 如何删除 youtube 品牌、视频信息和相关视频
- firebase - Firebase 动态链接自定义参数
- vba - 在幻灯片更改时更改 PowerPoint 上的媒体音量
- c# - 在 C# 的抽象类中重载运算符(如 +、-、*、/)
- reactjs - 如果提交时未选中复选框,我正在尝试显示错误消息