Alinwndrld
Alinwndrld

Reputation: 797

Is file closed or still in memory?

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

Upvotes: 3

Views: 195

Answers (2)

Raymond Hettinger
Raymond Hettinger

Reputation: 226524

In CPython, reference counting will cause the file to be closed immediately. In other versions of Python, it will stay open until the periodic garbage collector runs.

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994001

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.

Upvotes: 6

Related Questions