AttributeError: str object has no attribute write error occurs if we invoke ‘write’ attribute from str type object however it is not defined in the class of ‘str’ python data structure. This ‘write’ attribute/method is defined in the file type object. Basically when we open any file and want to write some text into it. Then use this write() function with file type object.
In this article, we will understand how to fix this error. We will also understand the correct way to use this write() type attribute. So lets start.
AttributeError: str object has no attribute write ( Solution ) –
The best way to start is to replicate this error with some examples. In the below example we have taken a str type of object sample_text and then invoke write() method from it. Hence this is throwing the above attributeerror.
Solution 1: Using File type object –
To solve this issue, we can change the caller object. Since the file type of the object supports this write() attribute. Hence we will use it. Please refer to the below solution.
sample_text="Data Science Learner" sample_file_name = 'sample.txt' with open(sample_file_name, 'w', encoding='utf-8') as file_obj : file_obj.write(sample_text)
Solution 2: Type checking and exception handling –
In most cases, we assume and expect at the run time, we will receive the file type of object. But due to logic error or input error, at run time the code encounters unexpected object type str. In this scenario, we will again get this AttributeError.
Similar Errors :
1.AttributeError: str object has no attribute append (Solved )
2.AttributeError: str object has no attribute get (Solved )
3.‘str’ object has no attribute ‘contains’ ( Solved )
4.AttributeError: ‘str’ object has no attribute ‘read’ ( Solved )
5.Attributeerror: ‘str’ object has no attribute ‘decode’ ( Solved )
Data Science Learner Team
Join our list
Subscribe to our mailing list and get interesting stuff and updates to your email inbox.