python - 属性错误 : '_io.TextIOWrapper' object has no attribute 'next' python

标签 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()

错误:

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'

最佳答案

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

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

第二个是(就像您粘贴的错误非常强烈暗示)文件对象 fo,一个文本文件对象,没有 next 方法.您正在使用为 Python 2.x 编写的教程,但您使用的是 Python 3.x。这对你来说不会很顺利。 (我相信 next was/maybe 在 Python 2.x 中有效,但在 3.x 中无效。)更确切地说,与 Python 3 中的 next 最相似。 x 是 readline,像这样:

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

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

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

或者,如果你想获得更多的 Python 风格,你可以使用 enumerate功能:

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

关于python - 属性错误 : '_io.TextIOWrapper' object has no attribute 'next' python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967509/

相关文章:

python - "End of statement expected "python中的字符串语法错误

python - 如何从任意长度的 Python3 字符串数组构建 QML ListElements

Python aiohttp : cancel async execution on met condition

python - statsmodels.tsa._STL.STL "Unable to determine period from endog"

python 2.7 : Ints as objects

oop - 指定要在许多函数结束时执行的操作

用于设置 Django 应用程序的 python 路径

python - 在 Python Flask 中,如何在取消转义之前访问完整的原始 URL

python - 显示股价上涨和下跌概率的 Pandas 系列函数

python - Python 中每个用户的排名