F.E. PPS Unit 4 Practical 2 solution

Practical 2: Program to Access a File After It has been Closed.

Problem Statement

Write a Python program to demonstrate accessing a file after it has been closed. The program should raise an error or handle the exception that occurs when trying to perform operations on a closed file.

Solution Code

				
					# Program to access a file after it is closed

# Open the file in read mode
file = open("sample.txt", "r")

# Read the content of the file
content = file.read()
print("File Content before closing:\n", content)

# Close the file
file.close()

# Attempting to read from the closed file (this will raise an error)
try:
    content_after_close = file.read()
except ValueError as e:
    print("\nError after closing the file:", e)

				
			

Output

  • The program successfully reads the content of the file while it is open.
  • After closing the file using file.close(), attempting to read from the file raises an error.
  • The error is caught in the try-except block and an appropriate message is printed.

Example output:

				
					File Content before closing:
these is the file
Error after closing the file: I/0 operation on closed file.
Process finished with exit code 0
				
			

Explanation

Below is the explanation of F.E. PPS Unit 4 Practical 2 solution where we have written Python program to demonstrate accessing a file after it has been closed.

  1. Opening and Reading the File:
    • The file is opened using open(“sample.txt”, “r”) in read mode.
    • The content of the file is read and printed using file.read().
  2. Closing the File:
    • The file.close() method is called to close the file after reading.
  3. Attempting to Access the Closed File:
    • After the file is closed, an attempt to read from it (file.read()) raises a ValueError.
    • The error is caught in a try-except block, and the exception message is printed.

Key Concepts Learned

  • File Closing:
    • Understanding how files are closed using file.close().
  • Handling Errors When Accessing Closed Files:
    • Using a try-except block to handle exceptions when attempting operations on a closed file.
Tech Amplifier Final Logo