Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2: AttributeError: 'file' object has no attribute 'strip'

I have a .txt document called new_data.txt. All data in this document separated by dots. I want to open my file inside python, split it and put inside a list.

output = open('new_data.txt', 'a')
output_list = output.strip().split('.')

But I have an error:

AttributeError: 'file' object has no attribute 'strip'

How can I fix this?

Note: My program is on Python 2

like image 546
Michael Avatar asked Jul 19 '13 09:07

Michael


1 Answers

First, you want to open the file in read mode (you have it in append mode)

Then you want to read() the file:

output = open('new_data.txt', 'r') # See the r
output_list = output.read().strip().split('.')

This will get the whole content of the file.

Currently you are working with the file object (hence the error).


Update: Seems like this question has received a lot more views since its initial time. When opening files, the with ... as ... structure should be used like so:

with open('new_data.txt', 'r') as output:
    output_list = output.read().strip().split('.')

The advantage of this is that there's no need to explicitly close the file, and if an error ever occurs in the control sequence, python will automatically close the file for you (instead of the file being left open after error)

like image 64
TerryA Avatar answered Nov 15 '22 02:11

TerryA