Safely Open and Close Files in Python



When working with files in Python programming, the common tasks we can perform are reading data, writing logs or processing content. If the files are not managed in a proper way then it leads to issues such as resource leaks, file corruption or unexpected errors. In this article, we'll explore the different ways to safely open and close files in Python.

Why file safety is important?

When we open a file in python then the operating system will allocate resources to handle the file. If the file is not closed correctly, then those resources might not be released properly which leads to below issues ?

  • Memory or resource leaks
  • Files will be locked in which other programs can't access
  • Data loss

Using with Statement

When we use the with statement with open() function, it ensures that the file is properly closed after its suite finishes, even if an exception is raised. This makes the with statement and open() function the safest and most recommended wayfor opening and closing files in Python.

Example

In this example, we are opening a file in read mode using the with statement -

file_path = r"D:\Tutorialspoint\Articles\file1.txt"

with open(file_path, 'r') as file:
    content = file.read()
    print(content)

Following is the output of the above program, if the file contains text -

Hello, welcome to Tutorialspoint.
Have a happy learning.

Using try...finally Block

The try...finally block in Python is used to perform actions such as closing a file without considering even an exception occurs. When using open() method without a context manager then it's essential to close the file in the finally block to avoid resource leaks.

Example

In this example, we are opening a file in read mode using the open() method, and we attempt to read the content inside a try block and ensure that the file is properly closed using the finally block -

file_path = r"D:\Tutorialspoint\Articles\file1.txt"
file = open(file_path, 'r')
try:
    content = file.read()
    print(content)
finally:
    file.close()

Following is the output of the above program, which used try...finally block -

Hello, welcome to Tutorialspoint.
Have a happy learning.

Using try...except...finally

The try...except...finally structure in Python is used for error-handling during file operations, which still ensures that the file is properly closed. This method is useful when we expect specific exceptions, such as FileNotFoundError or IOError, in which we can handle them easily while closing the file in the finally block.

Example

In this example, we will open and read a file. If the file is not found, then an exception will be raised and a message will be printed. The Finally block takes care to close the file if it was successfully opened -

file_path = r"D:\Tutorialspoint\Articles\file1.txt"
try:
   file = open(file_path, 'r')
   content = file.read()
   print(content)
except FileNotFoundError:
   print("Error: The file does not exist.")
except IOError:
   print("Error: An I/O error occurred.")
finally:
   try:
      file.close()
   except NameError:
      pass  # file was never opened

Following is the output of the above program -

Hello, welcome to Tutorialspoint.
Have a happy learning.

Using Path.open() from pathlib

The pathlib module in Python offers the Path.open() method which works similarly to the built-in open() method but integrates seamlessly with other pathlib operations. This method is safe and readable when used with the with statement for automatic file closing.

Example

In this example, we use the Path class from the pathlib module to open and read a file and the with statement ensures that the file is automatically closed after use -

from pathlib import Path

file_path = Path(r"D:\Tutorialspoint\Articles\file1.txt")

with file_path.open('r') as file:
    content = file.read()
    print(content)

Below is the output if the file contains some text -

Hello, welcome to Tutorialspoint.
Have a happy learning.
Updated on: 2025-05-02T19:03:11+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements