python - What happens if I read a file without closing it afterwards? -


i used read files this:

f = [i.strip("\n") in open("filename.txt")] 

which works fine. prefer way because cleaner , shorter traditional file reading code samples available on web (e.g. f = open(...) , line in f.readlines() , f.close()).

however, wonder if there can drawback reading files this, e.g. since don't close file, python interpreter handles itself? there should careful of using approach?

this recommended way:

with open("filename.txt") f:     lines = [line.strip("\n") line in f] 

the other way may not close input file long time. may not matter application.

the with statement takes care of closing file you. in cpython, letting file handle object garbage-collected should close file you, in other flavors of python (jython, ironpython, pypy) can't count on this. also, with statement makes intentions clear, , conforms common practice.


Comments

Popular posts from this blog

html5 - What is breaking my page when printing? -

html - Unable to style the color of bullets in a list -

c# - must be a non-abstract type with a public parameterless constructor in redis -