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

北慕城南 提交于 2019-12-19 06:19:02

问题


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?

** 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

回答1:


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




回答2:


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



回答3:


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):
    ...


来源:https://stackoverflow.com/questions/6618882/python-3-2-readline-is-skipping-lines-in-source-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!