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:
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.