简体   繁体   中英

How can I use nested for loops in Python-3.x to print from a text file one line at a time, x number of cycles?

I am attempting to print from a text file one line at a time, however many cycles I require. I am stuck here:

    def do():
        i = 0
        for i in range(int(mlt)):
            file = open('/some/dir/text.txt' , 'r')
            for line in file:
                linenumber = file.readline()
                time.sleep(1)
                print(linenumber)

    mlt = input('number of cycles')
    do()

This outputs to:

    line2

    line4

    line6

    line8

    line10

    line2

    line4
    ....

When I require:

    line1

    line2

    line3

    line4

    line5

    line6

    line7

    line8

    line9

    line10

    line1

    line2

    line3
    ...

I would greatly appreciate if someone could explain to me what it is I am doing wrong.

for line in file: and linenumber = file.readline() are doing the same thing which is why you are getting every second line. Try the following:

     for line in file:
            time.sleep(1)
            print(line)

You're iterating over the file with for line in file: , but then in each iteration you grab the next line with readline() , resulting in printing every other line. The double-spacing is because print() has a default end of a newline. To fix this, simply print every line in the file with no extra characters:

def do(num):
    for i in range(num):
        with open('/some/dir/text.txt' , 'r') as file:
            for line in file:
                time.sleep(1)
                print(line, end='')

mlt = input('number of cycles')
do(int(mlt))

I've also refactored your code a bit so the function takes an argument representing the number of times it should loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM