0

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)

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

4 Comments

And one more thing, is that if you are going to try calling FooIterator.__next__() yourself, you actually need to write it as FooIterator._FooIterator_next__(), because of the way the name mangling invoked by the __ prefix works.
@hcwhsa That's not what I exactly meant, Edit: Nevermind, got it
a = iter("hello"); a.__next__() works for me. Name mangling is only when the attribute starts with __ and doesn't end with it.
@user2802035 Use line = next(users) (which is what hcwhsa said).

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.