Python:AttributeError:'_io.TextIOWrapper'对象没有属性'split'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17569679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:33:28  来源:igfitidea点击:

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

pythonpython-3.x

提问by Kaizer von Maanen

I have a textfile, let's call it goodlines.txtand I want to load it and make a list that contains each line in the text file.

我有一个文本文件,让我们调用它goodlines.txt,我想加载它并制作一个包含文本文件中每一行的列表。

I tried using the split()procedure like this:

我尝试使用这样的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'

Why do I get these errors? Is that not how I use split()? ( I am using python 3.3.2)

为什么我会收到这些错误?我不是这样用的split()吗?(我正在使用python 3.3.2

采纳答案by Martijn Pieters

You are using strmethods on an open file object.

您正在str对打开的文件对象使用方法。

You can read the file as a list of lines by simply calling list()on the file object:

您可以通过简单地调用list()文件对象来将文件作为行列表读取:

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

This doesinclude 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]

回答by Sheng

Try this:

尝试这个:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open()function returns a file object. And for file object, there is no method like splitlines()or split(). You could use dir(f)to see all the methods of file object.

open()函数返回一个文件对象。而对于文件对象,没有像splitlines()or那样的方法split()。您可以使用dir(f)查看文件对象的所有方法。

回答by Samuele Mattiuzzo

You're not reading the file content:

您没有阅读文件内容:

my_file_contents = f.read()

See the docsfor further infos

有关更多信息,请参阅文档

You could, without calling read()or readlines()loop over your file object:

您可以不调用read()readlines()循环遍历您的文件对象:

f = open('goodlines.txt')
for line in f:
    print(line)

If you want a list out of it (without \nas you asked)

如果你想要一个列表(没有\n你问的)

my_list = [line.rstrip('\n') for line in f]