Python 3.2 - readline () skips lines in source file

I have a .txt file that I created with several lines.

when I run the for loop, with the count drive, it skips the lines.

He skips the top line and starts with the second, prints the fourth, sixth, etc.

What am I missing?

** 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 
+6
source share
3 answers

Try to delete "line = data_file.readline ()" in general? I suspect that "for a row in data_file:" is also a read operation.

+6
source

You repeat the data_file for the loop, and your readline () competes with it. Erase line = data_file.readline() 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 
+6
source

for line in data_file already gets the text of each line for you - a subsequent readline call then gets the next line. In other words, deleting the readline call will do what you want. At the same time, you don't need to track the battery variable yourself - python has a built-in way to do this with enumerate - in other words:

 data_file = open('line_numbers.txt', 'r') for count, line in enumerate(data_file): ... 
+3
source

Source: https://habr.com/ru/post/892281/


All Articles