lines = len(open(filename, 'r').readlines()) //or
open(filename, 'w').writelines(lines)
Does this lines in python, closes the opened file? If not how to close files which are not assigned to any variable? Also what these type of coding is called, is it "refcounting semantics"?
Python's garbage collector will clean up the open file objects some time after you've last used them (this may or may not be right away). It's best to be explicit, for example:
with open(filename, 'r') as f:
lines = len(f.readlines())
with open(filename, 'w') as f:
f.writelines(lines)
The standard CPython implementation uses reference counting and will tend to clean up objects very quickly. However, other implementations such as IronPython handle garbage collection differently and may not behave the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With