python - 如何在 Python27 中遍历文件而不遇到 ValueError 并用空行完全遍历文件?
问题描述
我基本上和这个人有同样的问题:人也有迭代问题
根据我所做的更改,我会遇到 IOError、ValueError(当我使用 for each 遍历文件中的每一行并使用 readline() 读取时),或者程序可以运行但它会切断我的数据当有空行时。我还尝试使用 for each 循环使用 .next() 而不是 readline 遍历文件,但这会跳过我数据集中的每一行。我相信那里的顶级评论可以解决我的问题,除了我的文本文件将有空行,这会过早结束 while 循环。解决这个问题的最佳方法是什么?是否有更好的数据结构可以使用,还是我必须以某种方式解析我的文件以删除空行?
这是我的一段代码,我正在使用 .rstrip() 去除每行末尾的换行符:
f = open(self.path,'r')
while True:
line = f.readline().rstrip()
temp_lines_list.append(line)
if not line:
break
一些示例输入:
text1 : 2380218302
test2 : sad
test3 : moresad (very)
yetanothertest : more datapoints
wowanewsection: incredible
我希望这有助于谢谢你:)
解决方案
你有没有尝试过这样的事情:
lines_output = []
with open('myFile.txt', 'r') as file: # maybe myFile.txt == self.path??
for line in file.readlines(): # we use readlines() instead of readline() so we iterate entire file
stripped_line = line.strip()
if stripped_line not '':
lines_output.append(stripped_line) # save info if line is not blank
else:
pass # if line is blank just skip it
推荐阅读
- javascript - 无法使用字符串作为参数从 PHP 调用 JavaScript 函数
- javascript - 尝试将语义 UI 中的按钮放入代码中时,不断收到错误消息。错误是错误:无法在未安装的组件上找到节点
- cmake - 使用现有目标作为新但相关目标的基础
- python - 优化代码以查找下一个素数
- apache-spark - 将 SQL 逻辑“OR EXISTS(子查询)”转换为 Spark 半连接
- python - 对使用多个模块进行日志记录的疑问
- node.js - 类型 '(number | Auth0User[])[]' 缺少来自类型 '[Auth0User[], number]' 的以下属性:0、1
- sql - 语法错误:预期输入结束,但在 bigquery 中的 [11:1] 处出现关键字 INSERT 错误
- html - Chrome 开发工具问题:元素选项卡 --> 样式 --> 排序问题
- logic - 推理与逻辑 CSE 1300 练习