如何在没有遇到ValueError的情况下迭代Python27中的文件并使用空行完全迭代文件?

问题描述 投票:0回答:2

我基本上和这个家伙有同样的问题:person also having issues iterating

根据我改变的内容,我将遇到一个IOError,一个ValueError(当我使用a来迭代文件中的每一行,并使用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

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

python python-2.7 file loops valueerror
2个回答
1
投票

readline()方法返回一个带有尾随换行符的行,即使在空行上也是如此。您应该在剥离线之前检查线是否为空:

while True:
    line = f.readline()
    if not line:
        break
    temp_lines_list.append(line.rstrip())

但是,在Python中使用文件对象作为迭代来遍历文件行更加惯用,因此您不必自己管理迭代。

for line in f:
    temp_lines_list.append(line.rstrip())

1
投票

你尝试过这样的事情:

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
© www.soinside.com 2019 - 2024. All rights reserved.