1

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 ?

2
  • 5
    Python interactive sessions always keep the result of the last expression around, bound to _. Commented Apr 24, 2019 at 8:18
  • 2
    @brunns Yep, that's it. To expand further, this means that when you just run open(path) and wait, then the file descriptor is stored in a variable, while open(path).read() binds the content of the file to a variable, but the file descriptor is not bound and can be garbage collected. Commented Apr 24, 2019 at 8:20

1 Answer 1

2

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")
Sign up to request clarification or add additional context in comments.

2 Comments

True, but that doesn't answer the question. See the comments on the question
Yes, Thanks you ! but I have learnt those things I want to know what was happened

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.