PYTHON

Python File Handling: Syntax, Usage, and Examples

Python file handling allows reading, writing, appending, and managing files directly from code. It enables working with text files, binary files, and logging mechanisms for data storage, retrieval, and manipulation.

How to Use File Handling in Python

Python provides built-in functions to open, read, write, and close files. The open() function serves as the primary method for handling files in Python.

file = open("filename.txt", mode)
  • "filename.txt" refers to the file name and location.
  • mode determines how the file is accessed (read, write, append, etc.).

When to Use File Handling in Python

Storing and Retrieving Data

Applications frequently need to store user preferences, logs, or results in files. File handling simplifies data storage and retrieval.

with open("data.txt", "w") as file:
    file.write("User preferences: Dark Mode Enabled")

Processing Large Files

Data analysis, logging, and automation tasks often require processing large text or CSV files.

with open("logfile.txt", "r") as file:
    for line in file:
        print(line.strip())  # Removes extra whitespace

Managing Configuration and Log Files

Applications generate logs to track system behavior and debug errors. File handlers in Python allow structured logging.

import logging

logging.basicConfig(filename="app.log", level=logging.INFO)
logging.info("Application started successfully")

Examples of File Handling in Python

Reading a File

Use the read() method to retrieve the entire file content.

with open("example.txt", "r") as file:
    content = file.read()
    print(content)

For line-by-line reading:

with open("example.txt", "r") as file:
    for line in file:
        print(line.strip())

Writing to a File

Use 'w' mode to write content.

with open("output.txt", "w") as file:
    file.write("Hello, Python!")

Appending to a File

Appending adds content without overwriting existing data.

with open("output.txt", "a") as file:
    file.write("\nNew line added.")

Handling File Exceptions

Catch errors to prevent crashes when a file doesn’t exist or access is restricted.

try:
    with open("non_existent_file.txt", "r") as file:
        print(file.read())
except FileNotFoundError:
    print("File not found. Please check the file path.")

Learn More About File Handling in Python

File Handling Methods

Python provides built-in methods for efficient file operations.

  • read(size): Reads the specified number of bytes.
  • readline(): Reads one line at a time.
  • readlines(): Reads all lines and returns a list.
  • write(string): Writes a string to the file.
  • writelines(list): Writes multiple lines at once.
  • seek(offset): Moves the cursor to a specific position.
  • tell(): Returns the current cursor position.

Example of seek() and tell():

with open("example.txt", "r") as file:
    file.seek(10)  # Move to the 10th character
    print(file.tell())  # Get current position

Using with to Handle Files

The with statement simplifies file handling by closing files automatically.

with open("example.txt", "r") as file:
    print(file.read())

Python Logging File Handler

Python’s logging module provides a structured way to store logs.

import logging

logger = logging.getLogger("app_logger")
file_handler = logging.FileHandler("application.log")
formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")

file_handler.setFormatter(formatter)
logger.addHandler(file_handler)

logger.setLevel(logging.INFO)
logger.info("Application started")

Working with Binary Files

Binary files store non-text content like images, audio, and videos. Use 'rb' and 'wb' modes to read and write them.

with open("image.png", "rb") as file:
    image_data = file.read()

with open("copy.png", "wb") as file:
    file.write(image_data)

Handling CSV Files

CSV files store structured data for easy processing. Python’s csv module simplifies reading and writing CSV files.

import csv

with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Name", "Age"])
    writer.writerow(["Alice", 25])

Reading a CSV file:

with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

Choosing the Right File Handling Mode

Using the correct file mode ensures smooth file operations.

  • 'r' allows safe file reading.
  • 'w' creates or overwrites a file.
  • 'a' appends data without modifying existing content.
  • 'rb' and 'wb' handle binary files.

Python file handling enables reading, writing, and managing files efficiently. Whether working with text, logs, binary data, or structured files like CSV, mastering file operations improves data management in applications. Understanding file handling methods, modes, and exception handling ensures reliable file interactions in Python programming.

Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2025 Mimo GmbH