readline() is skipping lines in source file
Asked Answered
N

3

10

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
Natascha answered 8/7, 2011 at 1:4 Comment(1)
I think @Shelhammer nailed it. I guess it's unobvious that "in" does a read. Well, it does.Take
P
13

Try removing the "line=data_file.readline()" altogether? I suspect the "for line in data_file:" is also a readline operation.

Podite answered 8/7, 2011 at 1:8 Comment(1)
Now its not skipping, but its counting blank lines on the output? so instead of 1-5, its returning 1 - 11Natascha
S
11

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:

# 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
Selfexplanatory answered 8/7, 2011 at 1:9 Comment(0)
A
4

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 using enumerate - in other words:

data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
    ...
Aarika answered 8/7, 2011 at 1:13 Comment(3)
And for the OP's edification, let's improve that even more better by using with open('line_numbers.txt') as data_file:Frangipane
+1 indeed for enumerate(). Don't forget it numbers from zero, so when printing for human consumption you often want to add one to the count. Most people are more comfortable with 1-based numbering.Fonda
Thank you guys. I'm in a class, thats teaching from "basics" but I will definitely put this in my notes!!Natascha

© 2022 - 2024 — McMap. All rights reserved.