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
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.
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.
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.
Using Continue statement. We use the 'continue' statement to skip the execution of the current iteration of the loop.
Try removing the "line=data_file.readline()" altogether? I suspect the "for line in data_file:" is also a readline operation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With