1

I wrote the following:

y=open('S:\\02012014EASTERN.TXT','r').readlines()

I don't know whether the file is now closed. How do I test this?

0

3 Answers 3

10

You can't test for this, because you never stored a reference to the file object.

It is better to use the file object as a context manager, which ensures that the file object will be closed:

with open('S:\\02012014EASTERN.TXT','r') as ofh:
    y = ofh.readlines()

Because CPython uses reference counting, in your code the file object would be immediately closed and cleared, but you cannot count on this behaviour in other Python implementations where garbage collection may be delayed.

3

While the other answers give you the best approach (using the 'with' statement), this is what you could do if you are curious:

f = open('S:\\02012014EASTERN.TXT','r')
y = f.readlines()
print(f.closed)
f.close()
print(f.closed)

The first 'print' statement will yield 'False' and the second one will yield 'True'.

But again, in "real" code use the 'with' construction instead. It will do the closing for you.

2

Use:

with open(file) as f:
     your code here

it'll ensure the file is closed by calling the __exit__ method after the with statement block ends.

Not the answer you're looking for? Browse other questions tagged or ask your own question.