File Handling Techniques in Day 19 of 30 Days of Python: A Complete Guide

Day 19 of the 30 Days of Python curriculum covers essential file handling techniques including the open() function with various modes, reading methods like read() and readlines(), writing and appending operations, safe file deletion using the os module, and parsing popular formats such as JSON, CSV, and XML.

The Asabeneh/30-Days-Of-Python repository provides a structured introduction to Python programming, with Day 19 focusing specifically on persistent data storage through file handling. This lesson demonstrates how to interact with the file system using Python's built-in functions and standard library modules to create, read, update, and delete files across multiple formats.

Opening Files with open() and Context Managers

The foundation of Day 19's file handling instruction rests on Python's built-in open() function and the context manager protocol. According to the source material in 19_Day_File_handling/19_file_handling.md, the curriculum emphasizes using the with statement to ensure files are automatically closed after operations complete, preventing resource leaks and file corruption.


# Safe file opening with automatic closure

with open('files/reading_file_example.txt') as f:
    content = f.read()
    print(content)

Understanding File Modes

The tutorial explains six distinct mode parameters that control how Python interacts with the file system:

  • r – Opens a file for reading (default mode, raises error if file doesn't exist)
  • a – Opens for appending, creating the file if it doesn't exist
  • w – Opens for writing, overwriting existing content or creating a new file
  • x – Exclusive creation, failing if the file already exists
  • t – Text mode (default), handling content as strings
  • b – Binary mode, handling content as bytes for non-text files

Reading File Contents

Day 19 introduces four distinct methods for retrieving data from text files, each suited to different processing scenarios. The 19_file_handling.md file demonstrates these approaches using files/reading_file_example.txt as a reference dataset.

read() returns the entire file content as a single string:

with open('files/reading_file_example.txt') as f:
    content = f.read()
    print(content)  # Entire file as one string

readline() retrieves a single line, maintaining the file pointer position for subsequent reads:

with open('files/reading_file_example.txt') as f:
    first_line = f.readline()
    print(first_line)  # Only the first line with newline character

readlines() returns a list where each element represents one line from the file:

with open('files/reading_file_example.txt') as f:
    lines = f.readlines()
    print(lines)  # ['First line\n', 'Second line\n', ...]

splitlines() removes newline characters by splitting the string at line boundaries:

with open('files/reading_file_example.txt') as f:
    lines = f.read().splitlines()
    print(lines)  # ['First line', 'Second line', ...] without \n

Writing and Appending to Files

The curriculum distinguishes between overwriting existing content and appending to it through mode selection. When using mode 'w', the write() method replaces existing data entirely, while mode 'a' adds content to the file's end.


# Overwrite or create new file

with open('files/writing_file_example.txt', 'w') as f:
    f.write('New content replaces old data.\n')
    f.write('Second line of new content.\n')

# Append to existing file

with open('files/reading_file_example.txt', 'a') as f:
    f.write('This line is appended at the end.\n')

Deleting Files Safely with os.remove()

Day 19 teaches defensive programming practices for file deletion using the os module. The recommended pattern checks for file existence before attempting removal to prevent FileNotFoundError exceptions.

import os

path = 'files/temporary.txt'

if os.path.exists(path):
    os.remove(path)
    print(f'{path} deleted successfully')
else:
    print('File does not exist')

Working with Structured Data Formats

Beyond plain text, the lesson covers parsing and writing industry-standard formats using Python's standard library and third-party packages.

JSON Serialization

Using the json module, the tutorial demonstrates dictionary serialization with json.dump() and deserialization with json.load():

import json

person = {'name': 'Asabeneh', 'city': 'Helsinki'}

# Write JSON with formatting

with open('files/person.json', 'w', encoding='utf-8') as f:
    json.dump(person, f, ensure_ascii=False, indent=4)

# Read back into dictionary

with open('files/person.json') as f:
    data = json.load(f)
    print(data['name'])  # Asabeneh

CSV Processing

The csv module's DictReader provides dictionary-based access to tabular data in files/csv_example.csv:

import csv

with open('files/csv_example.csv', newline='') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['name'], row['country'])

XML Parsing

For XML documents like files/xml_example.xml, the curriculum uses xml.etree.ElementTree to navigate hierarchical data:

import xml.etree.ElementTree as ET

tree = ET.parse('files/xml_example.xml')
root = tree.getroot()

print(root.tag)      # person

print(root.attrib)   # {'gender': 'female'}

for child in root:
    print(f'{child.tag}: {child.text}')

Summary

  • File modes (r, a, w, x, t, b) determine read, write, append, and binary operation capabilities when opening files with open().
  • Context managers (with statements) ensure automatic file closure and prevent resource leaks in production code.
  • Reading methods include read() for full content, readline() for single lines, and readlines()/splitlines() for list-based processing.
  • Safe deletion requires checking os.path.exists() before calling os.remove() to avoid runtime exceptions.
  • Structured formats (JSON, CSV, XML) are handled through standard library modules (json, csv, xml.etree.ElementTree) for robust data exchange.

Frequently Asked Questions

What file modes are taught in Day 19 of 30 Days of Python?

Day 19 covers six primary modes: r (read), a (append), w (write), x (exclusive creation), t (text), and b (binary). These modes control whether Python opens a file for reading, writing, or appending, and whether the content is treated as text strings or binary bytes.

How does the curriculum teach safe file deletion?

The tutorial recommends using os.path.exists() to verify a file's presence before calling os.remove(). This defensive pattern prevents FileNotFoundError exceptions and ensures idempotent deletion operations across different runtime environments.

Which file formats are covered beyond plain text?

In addition to .txt files, Day 19 provides practical examples for JSON (using the json module), CSV (using csv.DictReader), XML (using xml.etree.ElementTree), and references XLSX handling for Excel spreadsheets, demonstrating real-world data persistence scenarios.

Why is the with statement emphasized for file handling?

The with statement creates a context manager that automatically invokes close() on the file object when the block exits, even if exceptions occur. This eliminates manual resource management errors and is presented as the canonical pattern for production-grade file I/O in Python.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →