Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.2 - readline() is skipping lines in source file

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
like image 327
Alli OGrady Avatar asked Jul 08 '11 01:07

Alli OGrady


People also ask

How do you keep reading lines in Python?

To do that, first, open the file using Python open() function in read mode. The open() function will return a file handler. Use the file handler inside your for-loop and read all the lines from the given file line by line. Once done,close the file handler using close() function.

Does Python readline include newline?

In addition to the for loop, Python provides three methods to read data from the input file. The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.

How is method readline () different from readline () in Python?

Python readline() method will return a line from the file when called. readlines() method will return all the lines in a file in the format of a list where each element is a line in the file.

How do I know if Python skips a line of code?

Using Continue statement. We use the 'continue' statement to skip the execution of the current iteration of the loop.


1 Answers

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

like image 68
whiskeyfur Avatar answered Nov 01 '22 20:11

whiskeyfur