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:

ParameterDescription
filenameThe name or path of the file to open.
modeThe mode in which to open the file (e.g., read, write, append).

Common File Modes

ModeDescription
'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 file

Output (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 with block 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()

FeatureUsing open()Using with
File closingMust be done manually with close()Automatic after block execution
Error handlingFile might stay open if error occursAutomatically closes file even if error occurs
ReadabilityMore lines of codeCleaner and more Pythonic

🔹 In Summary

Function / KeywordPurpose
open()Opens a file and returns a file object for reading/writing.
withContext manager that handles opening and closing files automatically.
Best PracticeAlways use with open() to ensure proper file handling and avoid resource leaks.

In short:

  • Use open() to work with files.
  • Use with to automatically close them and write clean, safe code.

Scroll to Top