好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Python:AttributeError:’_ io.TextIOWrapper’对象没有属性’s

我有一个文本文件,我们称之为goodlines.txt,我想加载它并创建一个包含文本文件中每一行的列表.

我尝试使用split()过程,如下所示:

>>> f = open('goodlines.txt')
>>> mylist = f.splitlines()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'splitlines'
>>> mylist = f.split()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

为什么我会收到这些错误?这不是我如何使用split()? (我使用的是python 3.3.2)

您正在打开文件对象上使用str方法.

您只需在文件对象上调用list()即可将该文件作为行列表读取:

with open('goodlines.txt') as f:
    mylist = list(f)

这包括换行符.您可以在列表理解中删除它们:

with open('goodlines.txt') as f:
    mylist = [line.rstrip('\n') for line in f]

查看更多关于Python:AttributeError:’_ io.TextIOWrapper’对象没有属性’s的详细内容...

  阅读:66次