Python:AttributeError:'_io.TextIOWrapper'对象没有属性'split' [英] Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

查看:235
本文介绍了Python:AttributeError:'_io.TextIOWrapper'对象没有属性'split'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我尝试使用这样的 split() 过程:

<预><代码>>>>f = open('goodlines.txt')>>>mylist = f.splitlines()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: '_io.TextIOWrapper' 对象没有属性 'splitlines'>>>mylist = f.split()回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中AttributeError: '_io.TextIOWrapper' 对象没有属性 '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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆