AttributeError:'_ io.TextIOWrapper'对象没有属性'next'python

19 python

我正在使用python 3.3.3.我正在从tutorialspoint.com上做教程.我无法理解这个错误是什么.

这是我的代码:

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()
Run Code Online (Sandbox Code Playgroud)

错误:

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'
Run Code Online (Sandbox Code Playgroud)

fur*_*kle 28

你在这里遇到问题有两个原因.首先是您fo以只写模式创建.您需要一个可以读写的文件对象.您也可以使用该with关键字在完成后自动销毁文件对象,而不必担心手动关闭它:

# the plus sign means "and write also"
with open("foo.txt", "r+") as fo:
    # do write operations here
    # do read operations here
Run Code Online (Sandbox Code Playgroud)

第二个是(就像你已经非常强烈地粘贴的错误所表明的那样)文件对象fo(文本文件对象)没有next方法.您正在使用为Python 2.x编写的教程,但您使用的是Python 3.x. 这对你来说并不顺利.(我相信next是/可能在Python 2.x中有效,但它不在3.x中.)相反,next在Python 3.x中最类似的是readline,如下所示:

for index in range(7):
    line = fo.readline()
    print("Line No %d - %s % (index, line) + "\n")
Run Code Online (Sandbox Code Playgroud)

请注意,这仅在文件至少有7行时才有效.否则,您将遇到异常.迭代文本文件的更安全,更简单的方法是使用for循环:

index = 0
for line in file:
    print("Line No %d - %s % (index, line) + "\n")
    index += 1
Run Code Online (Sandbox Code Playgroud)

或者,如果你想获得更多pythonic,你可以使用枚举函数:

for index, line in enumerate(file):
    print("Line No %d - %s % (index, line) + "\n")
Run Code Online (Sandbox Code Playgroud)


小智 5

除了"r+"其他人提到的文件模式问题之外,OP引用的错误消息的发生是因为该f.next()方法在Python 3.x中不再可用。它似乎已被内置函数“next()”(https://docs.python.org/3/library/functions.html#next)所取代,该函数调用.__next__()迭代器的方法。

您可以在代码中的方法中添加下划线line = fo.__next__()- 但最好使用内置函数:line = next(fo)

我知道这是一个老问题 - 但我觉得包含这个答案很重要。