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
1
  • I think @Shelhammer nailed it. I guess it's unobvious that "in" does a read. Well, it does. Commented Jul 8, 2011 at 1:12

3 Answers 3

13

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

1
  • Now its not skipping, but its counting blank lines on the output? so instead of 1-5, its returning 1 - 11 Commented Jul 8, 2011 at 1:12
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
0
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):
    ...
3
  • And for the OP's edification, let's improve that even more better by using with open('line_numbers.txt') as data_file: Commented Jul 8, 2011 at 1:51
  • +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.
    – holdenweb
    Commented Jul 8, 2011 at 1:57
  • Thank you guys. I'm in a class, thats teaching from "basics" but I will definitely put this in my notes!! Commented Jul 8, 2011 at 1:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.