Reputation: 308
I am using python 3.7 ( on windows 10 ) I execute following line on terminal.
open('textfile.txt')
After I try to delete the file ('textfile.txt') then os said It is being used by some program. I close the terminal and open a new terminal then I execute following code
open('textfile.txt').read()
I try to delete the file ('textfile.txt') then It's deleted. My problem is both times I did't assign file object to any variable but first time file didn't close automatically second time It was happend.
Why second time python close the file automatically ?
Upvotes: 1
Views: 75
Reputation: 1886
If you open a File, you have to close
f = open('textfile.txt')
f.close()
Or used pythonic way:
with open("textfile.txt") as f:
d = f.read()
#On exit with code indent it will close
print("Here the file is closed automatically")
Upvotes: 2