Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is file closed or still in memory?

Tags:

python

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"?

like image 259
Alinwndrld Avatar asked Dec 01 '25 13:12

Alinwndrld


1 Answers

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.

like image 130
Greg Hewgill Avatar answered Dec 04 '25 04:12

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!