Home > Enterprise >  Is there a defined behaviour for closing a file inside a 'with open' statement in python?
Is there a defined behaviour for closing a file inside a 'with open' statement in python?

Time:12-08

If you have a file opened with a with open block, then you close the file inside that block, is there a defined behaviour? By my testing, there is no exception raised, but are there any reasons not to?

with open('foo', 'w') as f:
    f.write('some data')
    f.close()
    print('file is closed')
with open('foo') as f:
    print(f.read())

I ask as in some cases I will need to delete the opened file, so would want to close it first, but code will be cleaner to keep inside the with block. Alternatives might be to ditch the with open and just use the open function, or alternately set a flag to delete the file after the with block.

CodePudding user response:

Closing an already-closed file is an allowed no-op.

Also see some prior discussion on StackOverflow.

That said, what you're doing sounds odd to me. I would take your question as a prompt to consider whether you truly want/need the design you think you need.

CodePudding user response:

At the end of the with statement Python will automatically close the file. You don't need to call close() on it. With statement docs.

with open('file.txt', 'r') as f:
    print(f.closed)
print(f.closed)

Outputs:

False
True

Assuming you don't want to delete the opened file inside of your with statement there is no reason to call close().

  • Related