Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

like image 758
Kaizer von Maanen Avatar asked Jul 10 '13 11:07

Kaizer von Maanen


People also ask

Has no attribute split Python?

The Python "AttributeError: 'list' object has no attribute 'split'" occurs when we call the split() method on a list instead of a string. To solve the error, call split() on a string, e.g. by accessing the list at a specific index or by iterating over the list. Here is an example of how the error occurs. Copied!

What is _IO TextIOWrapper in Python?

TextIOWrapper , which extends TextIOBase , is a buffered text interface to a buffered raw stream ( BufferedIOBase ). Finally, StringIO is an in-memory stream for text.

What is _IO TextIOWrapper object?

The Python "TypeError: '_io. TextIOWrapper' object is not subscriptable" occurs when we try to use square brackets to access a key or index in a file object. To solve the error, use the readlines() method if you need a list of the file's lines, or parse the JSON before accessing a key.


1 Answers

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] 
like image 146
Martijn Pieters Avatar answered Sep 21 '22 00:09

Martijn Pieters