+ 1

python files

Hello. I tried opening, reading, printing, and closing a python file using this code: file = open("basic.py", "r+") file = file.read() print(file) file.close() However, I got this: AttributeError: 'str' object has no attribute 'close' Can anyone help to explain the situation?

9th Sep 2020, 3:45 PM
teemran
teemran - avatar
2 Answers
+ 1
Hi @Omar Falk, you are very right. Thanks, I did not observe this.
10th Sep 2020, 9:20 AM
teemran
teemran - avatar
+ 8
Hi, you use file for two different purposes. 1. here--> file = open("basic.py", "r+") 2.--> here file = file.read() print(file) file.close() With 2. you overwrite first use and your variable file is not a file handler but a string. Solution: Use different variables. for 2nd for example the variable content
9th Sep 2020, 3:57 PM
Oma Falk
Oma Falk - avatar