How can I check if my file is closed or not?


#1

Question

How can I check if my file is closed or not?

Answer

And if statement looks like this:

if some_expression:
  # Run this code!

The value stored in the file’s closed attribute will be either True or False, so we can directly check it in our if statement, like this:
if file_var.closed:
However, we want to check if it is not closed, so you’ll need to alter the expression slightly. Then, be sure to indent the code you want inside of your if statement using 2 spaces.


Learn Python - File Input / Output - Case Closed?