In Python, the open() function and the with statement are used for file handling — i.e., to read, write, or modify files.
They are an essential part of working with external files such as text files, logs, or CSV data.
🔹 open() Function
The open() function is used to open a file and returns a file object that can be used to perform operations like reading or writing.
Syntax:
open(filename, mode)Parameters:
| Parameter | Description |
|---|---|
filename | The name or path of the file to open. |
mode | The mode in which to open the file (e.g., read, write, append). |
Common File Modes
| Mode | Description |
|---|---|
'r' | Read mode (default). Opens file for reading. |
'w' | Write mode. Overwrites the file if it exists. |
'a' | Append mode. Adds new data to the end of the file. |
'x' | Creates a new file; raises an error if file exists. |
'r+' | Read and write mode. |
'b' | Binary mode (e.g., 'rb', 'wb'). |
't' | Text mode (default). |
🧩 Example 1: Opening and Reading a File
# Open a file in read mode
file = open("sample.txt", "r")
content = file.read()
print(content)
file.close() # Always close the fileOutput (example):
Hello, this is a sample text file.🧩 Example 2: Writing to a File
file = open("example.txt", "w")
file.write("Hello, Dheeraj!\nWelcome to Python file handling.")
file.close()Output:
A new file example.txt will be created with the written text.
🧩 Example 3: Appending Data to a File
file = open("example.txt", "a")
file.write("\nThis line is appended later.")
file.close()Output (file content):
Hello, Dheeraj!
Welcome to Python file handling.
This line is appended later.🔹 The with Statement (Context Manager)
The with statement simplifies file handling by automatically closing the file once the block of code is executed — even if an error occurs.
It’s considered best practice for file I/O operations.
Syntax:
with open(filename, mode) as variable:
# perform file operations🧩 Example 4: Reading a File Using with
with open("sample.txt", "r") as file:
data = file.read()
print(data)Output:
Hello, this is a sample text file.Explanation:
- The file is automatically closed when the
withblock ends. - You don’t need to call
file.close()manually.
🧩 Example 5: Writing with with Statement
with open("notes.txt", "w") as file:
file.write("This file was written using 'with' statement.")Output:
A new file notes.txt is created and automatically closed after writing.
🧩 Example 6: Reading File Line by Line
with open("sample.txt", "r") as file:
for line in file:
print(line.strip())Output:
Hello, this is a sample text file.🧩 Example 7: Handling Binary Files
with open("image.jpg", "rb") as file:
content = file.read()
print("File size:", len(content), "bytes")Output:
File size: 20480 bytes🔹 Advantages of Using with Over open()
| Feature | Using open() | Using with |
|---|---|---|
| File closing | Must be done manually with close() | Automatic after block execution |
| Error handling | File might stay open if error occurs | Automatically closes file even if error occurs |
| Readability | More lines of code | Cleaner and more Pythonic |
🔹 In Summary
| Function / Keyword | Purpose |
|---|---|
open() | Opens a file and returns a file object for reading/writing. |
with | Context manager that handles opening and closing files automatically. |
| Best Practice | Always use with open() to ensure proper file handling and avoid resource leaks. |
✅ In short:
- Use
open()to work with files.- Use
withto automatically close them and write clean, safe code.
