There's two reasons you're running into issues here. The first is that you've created fo
in write-only mode. You need a file object that can read and write. You can also use the with
keyword to automatically destruct a file object after you're done with it, rather than having to worry about closing it manually:
# the plus sign means "and write also"
with open("foo.txt", "r+") as fo:
# do write operations here
# do read operations here
The second is that (like the error you've pasted very strongly suggests) the file object fo
, a text file object, doesn't have a next
method. You're using an tutorial written for Python 2.x, but you're using Python 3.x. This isn't going to go well for you. (I believe next
was/maybe is valid in Python 2.x, but it is not in 3.x.) Rather, what's most analogous to next
in Python 3.x is readline
, like so:
for index in range(7):
line = fo.readline()
print("Line No %d - %s % (index, line) + "\n")
Note that this will only work if the file has at least 7 lines. Otherwise, you'll encounter an exception. A safer, and simpler way of iterating through a text file is with a for loop:
index = 0
for line in file:
print("Line No %d - %s % (index, line) + "\n")
index += 1
Or, if you wanted to get a little more pythonic, you could use the enumerate function:
for index, line in enumerate(file):
print("Line No %d - %s % (index, line) + "\n")
You are not following the tutorial correctly. You have opened the file Write only open("foo.txt", "w")
The action line = fo.next()
is a read, so obviously it will crash.
So fix it by opening as write and read: fo = open("foo.txt", "r+")
But that's only for Python 2.7, you should probably use next or fix the iteration via an other way. Check @furkle's answer.
The tutorial is probably also incorrect, see explanation of the modes here: python open built-in function: difference between modes a, a+, w, w+, and r+?
You can use fo.\__next__()
or fo.next()
in python3.x.
In Addition to the file mode issue "r+"
which others have mentioned, the error message quoted by the OP happens because the f.next()
method is no longer available in Python 3.x. It appears to have been replaced by the built in function 'next()' (https://docs.python.org/3/library/functions.html#next) which calls the .__next__()
method of an iterator.
You could add the underscores to the method in your code line = fo.__next__()
- but it is probably best to use the built in function: line = next(fo)
I know this is an old question - but I felt it important to include this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With