0

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.

1
  • print adds a carriage return. try print(linenumber.strip('\n')) or ('\r') depending on what sort of crs your system is using. Commented Oct 26, 2015 at 3:15

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.