user1431282
user1431282

Reputation: 6845

Python Flushing and Already Closed File

How do I add a check to avoid flushing a file f with f.flush() when some function has already done f.close()?

I can't seem to figure out how to do so :/

Upvotes: 2

Views: 942

Answers (2)

mechmind
mechmind

Reputation: 1767

Just examine closed attribute of file object.

Upvotes: 3

Artsiom Rudzenka
Artsiom Rudzenka

Reputation: 29121

You can use try ...except for this purpose i guess

Any operation which requires that the file be open will raise a ValueError after the file has been closed

OR use fileobj.closed property and if it True then don't do flush

file.closed bool indicating the current state of the file object. This is a read-only attribute; the close() method changes the value. It may not be available on all file-like objects.

Upvotes: 3

Related Questions