我有一个用多行创建的.txt文件。
当我使用计数累加器运行for循环时,它会跳过行。
它跳过顶行,从第二行开始,打印第四,第六等......
我错过了什么?
** for your reading pleasure**
def main():
# Open file line_numbers.txt
data_file = open('line_numbers.txt', 'r')
# initialize accumulatior
count = 1
# Read all lines in data_file
for line in data_file:
# Get the data from the file
line = data_file.readline()
# Display data retrieved
print(count, ": ", line)
# add to count sequence
count += 1
答案 0 :(得分:9)
尝试完全删除“line = data_file.readline()”?我怀疑“for data in data_file:”也是一个readline操作。
答案 1 :(得分:9)
你循环遍历data_file并且你的readline()正在与它竞争。为此结果删除代码的line = data_file.readline()
行:
# Read all lines in data_file
count = 1
for line in data_file:
# Display data retrieved
print(count, ": ", line)
# add to count sequence
count += 1
答案 2 :(得分:4)
for line in data_file
已经为您获取了每行的文本 - 随后调用readline然后获取跟随行。换句话说,删除对readline的调用将执行您想要的操作。同时,您不需要自己跟踪累加器变量 - python有一种使用enumerate
执行此操作的内置方式 - 换句话说:
data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
...