Python 2: AttributeError: object 'file' does not have attribute 'strip'

I have a .txt document called new_data.txt . All data in this document is separated by dots. I want to open a file inside python, split it and paste it into the 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 in Python 2

+4
source share
1 answer

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

Then you want to read() file:

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

This will get all the contents of the file.

You are currently working with a file object (hence the error).


Update: this question seems to have received far more views from the start. When opening files, the with ... as ... structure should be used as follows:

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

The advantage of this is that there is 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 keeping the file open after the error)

+16
source

Source: https://habr.com/ru/post/1492265/


All Articles