josh
josh

Reputation: 1205

Python: Read next line in a file in one simple line of code

As the title says, I would like to use a simple command to make Python read the next line of a text file.
For example something like this:

users = open("C:\\Users\\Tharix\\Desktop\\test.txt",mode="r")
line = test.readline(20)
print(line)
line.next() #Or something similar
print(line)

(PS: I don't know this helps, but I'm using version 3.3.2 of Python)

Upvotes: 0

Views: 4335

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250951

Simply iterate over the file object:

with open("C:\\Users\\Tharix\\Desktop\\test.txt", mode="r") as users:
    for line in users:
       print(line)

Note that iter.next() has been renamed to iter.__next__() in py3.x, or better use next(iter).(This works in both py2.7, py3.x)

Upvotes: 5

Related Questions