Chapter 8: File Handling in Python – Reading & Writing Files

Previous Chapter Table of Contents Next Chapter

1. File Handling Basics

File Handling Diagram

The file handling process in Python

File Operations Workflow

  1. Open a file (creates file object)
  2. Read/Write data
  3. Close the file (release resources)
Always close files to prevent memory leaks and data corruption.

2. File Modes

Read Mode 'r'

Open for reading (default)

file = open("data.txt", "r")

Write Mode 'w'

Open for writing (overwrites)

file = open("data.txt", "w")

Append Mode 'a'

Open for appending

file = open("data.txt", "a")

Read/Write 'r+'

Open for both reading and writing

file = open("data.txt", "r+")

Exercise 1: File Mode Practice

Create a program that:

  1. Writes three lines to a new file output.txt
  2. Then reads and prints the file contents

3. Reading Files

Method 1: read()

Read entire file at once

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

Method 2: readlines()

Read as list of lines

with open("data.txt", "r") as file:
    lines = file.readlines()
    for line in lines:
        print(line.strip())
For large files, read line by line to avoid memory issues.

4. Writing Files

Write Mode 'w'

Overwrites existing content

with open("log.txt", "w") as file:
    file.write("New log entry\n")

Append Mode 'a'

Adds to existing content

with open("log.txt", "a") as file:
    file.write("Another entry\n")

Exercise 2: CSV Writer

Create a program that:

  1. Writes a list of dictionaries to CSV
  2. Format: Name,Age,Occupation
  3. Include headers

5. Essential File Methods

Method Description Example
read(size) Reads specified bytes file.read(100)
readline() Reads single line file.readline()
write() Writes string to file file.write("text")
seek() Changes file position file.seek(0)
tell() Returns current position file.tell()
Previous Chapter Next Chapter