readline() 正在跳过源文件中的行
我有一个用多行创建的 .txt 文件。
当我使用计数累加器运行 for 循环时,它会跳过行。
它跳过顶行,从第二行开始,打印第四行、第六行等。
我错过了什么?
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
I have a .txt file that I created with multiple lines.
When I run a for loop, with a count accumulator, it skips lines.
It skips the top line, and starts with the second, prints the fourth, the sixth, etc.
What is it I'm missing?
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试完全删除“line=data_file.readline()”?我怀疑“for line in data_file:”也是一个 readline 操作。
Try removing the "line=data_file.readline()" altogether? I suspect the "for line in data_file:" is also a readline operation.
您的 for 循环正在迭代 data_file 并且您的 readline() 正在与之竞争。删除代码中的
line = data_file.readline()
行以获得此结果:You for loop is iterating over the data_file and your readline() is competing with it. Erase the
line = data_file.readline()
line of your code for this result:for line in data_file
已经为您获取了每行的文本 - 随后对 readline 的调用将获取下面行。换句话说,删除对 readline 的调用将执行您想要的操作。同时,您不需要自己跟踪累加器变量 - python 有一个使用enumerate
执行此操作的内置方法 - 换句话说:for line in data_file
already gets the text of each line for you - the subsequent call to readline then gets the following line. In other words, removing the call to readline will do what you want. At the same time, you don't need to keep track of an accumulator variable yourself - python has a built-in way of doing this usingenumerate
- in other words: