I am using python 3.3.3. I am doing the tutorial from tutorialspoint.com. I am unable to understand what this error is.
Here is my code:
fo = open("foo.txt", "w")
print ("Name of the file: ", fo.name)
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
seq = ["This is 6th line\n", "This is 7th line"]
# Write sequence of lines at the end of the file.
fo.seek(0, 2)
line = fo.writelines( seq )
# Now read complete file from beginning.
fo.seek(0,0)
for index in range(7):
# line = fo.next()
print ("Line No %d - %s" % (index, line)+"\n")
# Close opend file
fo.close()
Error:
Name of the file: foo.txt
Traceback (most recent call last):
File "C:/Users/DELL/Desktop/python/s/fyp/filewrite.py", line 19, in <module>
line = fo.next()
AttributeError: '_io.TextIOWrapper' object has no attribute 'next'
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")
所有评论(0)