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.
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.
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)
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.
3.‘str’ object has no attribute ‘contains’ ( Solved )
Thanks
Data Science Learner Team