[python] 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)

This question is related to python python-3.x

The answer is


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.


You're not reading the file content:

my_file_contents = f.read()

See the docs for further infos

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

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

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

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