Python:AttributeError:'_io.TextIOWrapper'对象没有属性'split' [英] Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
问题描述
我有一个文本文件,我们称之为 goodlines.txt
,我想加载它并制作一个包含文本文件中每一行的列表.
我尝试使用这样的 split()
过程:
为什么会出现这些错误?这不是我使用 split()
的方式吗?(我正在使用 python 3.3.2
)
您正在对打开的文件对象使用 str
方法.
您可以通过简单地调用文件对象上的 list()
将文件作为行列表读取:
with open('goodlines.txt') as f:mylist = 列表(f)
这确实包括换行符.你可以在列表理解中去掉那些:
with open('goodlines.txt') as f:mylist = [line.rstrip('\n') for line in f]
I have a textfile, let's call it goodlines.txt
and I want to load it and make a list that contains each line in the text file.
I tried using the split()
procedure like this:
>>> 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'
Why do I get these errors? Is that not how I use split()
? ( I am using python 3.3.2
)
You are using str
methods on an open file object.
You can read the file as a list of lines by simply calling list()
on the file object:
with open('goodlines.txt') as f:
mylist = list(f)
This does include the newline characters. You can strip those in a list comprehension:
with open('goodlines.txt') as f:
mylist = [line.rstrip('\n') for line in f]
这篇关于Python:AttributeError:'_io.TextIOWrapper'对象没有属性'split'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!