w3resource

Python File I/O: Assess if a file is closed or not


16. File Closed Check

Write a Python program to assess if a file is closed or not.

Sample Solution:-

Python Code:

 f = open('abc.txt','r')
print(f.closed)
f.close()
print(f.closed)

Sample Output:

False                                                                                                         
True

Flowchart:

Flowchart: File I/O: Assess if a file is closed or not.

For more Practice: Solve these Related Problems:

  • Write a Python program to open a file, close it, and then check if the file is closed using the 'closed' attribute.
  • Write a Python script to open a file using a with-statement and verify it is automatically closed after the block.
  • Write a Python program to check if a file is open or closed before performing any read or write operations.
  • Write a Python function that opens a file, performs a read operation, and then asserts that the file is closed afterwards.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to read a random line from a file.
Next: Write a Python program to remove newline characters from a file.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.