首页 > 解决方案 > 如何在 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

我希望这有助于谢谢你:)

标签: pythonpython-2.7fileloopsvalueerror

解决方案


你有没有尝试过这样的事情:

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

推荐阅读