Back to Python Notes
Topic #207

File Handling in Python

Master reading and writing files in Python using the open() function and context managers to ensure safe resource handling.

What it is

File handling allows programs to interact with data stored on a disk. In Python, this involves opening a file, performing operations (reading or writing), and closing the file to release system resources. The core object used is the file object, created via the built-in open() function. Related terms include "modes" (how the file is opened) and "context managers" (automatic cleanup).

Why it matters

  • Data Persistence: Save program state or results so they survive after execution ends.
  • Configuration Management: Read settings from external files without hardcoding values.
  • Resource Safety: Properly closing files prevents memory leaks and locked file errors.
  • Interoperability: Exchange data with other applications using standard text formats like CSV or JSON.

Syntax or steps

The most robust pattern uses the with statement, which acts as a context manager. This ensures the file closes automatically, even if an error occurs during processing.

  1. Call open(filename, mode). Common modes are 'r' (read), 'w' (write/overwrite), and 'a' (append).
  2. Assign the result to a variable within a with block.
  3. Use methods like .read(), .write(), or iterate over lines inside the block.
  4. The file closes automatically when the block exits.

Example

# Writing to a file
filename = 'example.txt'

# 1. Write data (mode 'w' creates or overwrites)
with open(filename, 'w') as file:
    file.write("Hello, World!\n")
    file.write("Python file handling is simple.")

# 2. Read data back (mode 'r' is default)
with open(filename, 'r') as file:
    content = file.read()
    print(content)

# Output:
# Hello, World!
# Python file handling is simple.

Explanation: The first block opens example.txt for writing. Two strings are added. The second block opens the same file for reading. file.read() loads the entire content into the variable content, which is then printed. Note that \n adds a new line.

Common mistakes

  • Forgetting to close files: Using open() without with or .close() can leave files locked. Always prefer with.
  • Wrong Mode: Opening a file in 'w' mode deletes existing content immediately. Use 'a' to add to the end instead.
  • Reading Binary as Text: Trying to read images or PDFs with 'r' causes decoding errors. Use 'rb' for binary files.
  • Path Errors: Assuming the file exists in the current directory. Use absolute paths or check existence with os.path.exists().

When to use it

Compare manual handling with context managers below:

FeatureManual (open()/close())Context Manager (with)
Code LengthLonger (requires explicit close)Shorter and cleaner
Error HandlingRisky (file may stay open on crash)Safe (auto-closes on exception)
Best ForComplex logic requiring multiple opens/closesStandard read/write operations

Use with statements for almost all file operations unless you have a specific reason to manage the lifecycle manually.

Practice

Guided Exercise: Create a script that writes your name and age to profile.txt, then reads it back and prints each line separately using a loop.

Challenge: Modify the script to append a favorite color to the file without deleting the previous content. Hint: Change the mode from 'w' to 'a'.

Quick check

Q: What happens if you try to write to a file opened in 'r' mode?

A: Python raises an io.UnsupportedOperation or OSError because the file handle is read-only.

Summary

Python’s file handling relies on the open() function and appropriate modes. Using the with context manager is the best practice to ensure files are properly closed and resources are freed, preventing data loss and system errors.

Want to go beyond the notes?

Join Coding Now Tech Institute's Python course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

File Handling in Python – FAQs

Quick answers about learning File Handling in Python in Python.

This free note from Coding Now Tech Institute explains File Handling in Python in Python — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every Python topic on Coding Now Tech Institute, including File Handling in Python, is 100% free with no signup required.
With focused practice, most students grasp File Handling in Python in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now