Skip to content

Computer Science · Ch 2 — File Handling in Python

Opening a file using with clause

2.3.3

Opening a file using with clause

The with clause in Python provides a cleaner and safer way to work with files. Its real power is that it handles file closing automatically — you never have to remember to call close().

The syntax is:

with open(file_name, access_mode) as file_object:

Here, file_name is the name of the file (as a string), access_mode is the mode in which you want to open it (like 'r', 'w', 'r+', etc.), and file_object is the variable name you assign to work with the file inside the block.

The key advantage: once the indented block under the with statement finishes executing — whether normally or because of an exception — the file is closed automatically. You do not need to write an explicit close() call. This eliminates two common problems: forgetting to close a file, and leaving a file open if an error occurs partway through.

For example:

with open("myfile.txt", "r+") as myObject:
    content = myObject.read()
``` …