Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Opening files without closing them. #2

Open
guettli opened this issue Oct 11, 2016 · 1 comment
Open

Opening files without closing them. #2

guettli opened this issue Oct 11, 2016 · 1 comment

Comments

@guettli
Copy link

guettli commented Oct 11, 2016

I often use this:

content=open(file_name).read()

According to your page "python improvements" this should be avoided, since the file does not get closed explicitly.

I don't understand it, since I think the open file gets closed as soon as the variable gets garbage collected.

What do you think? Is above line clean code?

@svisser
Copy link
Owner

svisser commented Oct 11, 2016

since I think the open file gets closed as soon as the variable gets garbage collected.

I don't know exactly. You may be right but I don't know whether Python will call close() when that line of code (or scope?) is over (because the opened file object after that no longer "exists").

Could it be that the file handler (internally) is kept open for a bit longer - until the next garbage collection or until the end of the process?

If you ensure that close() is called explicitly then at least it removes this uncertainty for anyone reading the code. Without it you'd need to be aware of how Python does this behind the scenes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants