Tutorials Logic, IN info@tutorialslogic.com

Python File Handling Read, Write, Append Files

Python Files

File handling lets Python read existing data, write new output, append logs, and work with project files.

Use with open(...) so files are closed automatically even if an error happens while reading or writing.

Most beginner file issues come from the wrong path, missing files, wrong mode, or unexpected text encoding.

Working with Files

Python makes file I/O straightforward with the built-in open() function. Always use the with statement - it automatically closes the file even if an error occurs.

File Modes

Mode Description
'r' Read (default) - error if file doesn't exist
'w' Write - creates file or overwrites existing
'a' Append - adds to end of file
'x' Create - error if file already exists
'r+' Read and write
'b' Binary mode (e.g., 'rb', 'wb')
't' Text mode (default)

Read Files

Read Whole Files and Lines

Read Whole Files and Lines
# Read entire file as a string
with open("data.txt", "r") as f:
    content = f.read()
    print(content)

# Read line by line (memory-efficient for large files)
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())   # strip() removes trailing newline

# Read all lines into a list
with open("data.txt", "r") as f:
    lines = f.readlines()
    print(lines)   # ['line1\n', 'line2\n', ...]

# Read one line at a time
with open("data.txt", "r") as f:
    first_line = f.readline()
    second_line = f.readline()

# Specify encoding (important for non-ASCII text)
with open("data.txt", "r", encoding="utf-8") as f:
    content = f.read()

Write Files

Write, Append, and Print to Files

Write, Append, and Print to Files
# Write (overwrites existing content)
with open("output.txt", "w") as f:
    f.write("Hello, World!\n")
    f.write("Second line\n")

# Write multiple lines at once
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as f:
    f.writelines(lines)

# Append to existing file
with open("log.txt", "a") as f:
    f.write("New log entry\n")

# Write with print() - convenient for formatted output
with open("report.txt", "w") as f:
    print("Report Title", file=f)
    print(f"Total: {42}", file=f)

JSON Files

Write and Read JSON Data

Write and Read JSON Data
import json

# Write JSON to file
data = {
    "name": "Alice",
    "age": 25,
    "hobbies": ["coding", "reading"]
}

with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

# Read JSON from file
with open("data.json", "r") as f:
    loaded = json.load(f)

print(loaded["name"])     # Alice
print(loaded["hobbies"])  # ['coding', 'reading']

# Write list of records
users = [
    {"id": 1, "name": "Alice"},
    {"id": 2, "name": "Bob"},
]
with open("users.json", "w") as f:
    json.dump(users, f, indent=2)

CSV Files

Write and Read CSV Rows

Write and Read CSV Rows
import csv

students = [
    ["Name", "Age", "Grade"],
    ["Alice", 20, "A"],
    ["Bob", 22, "B"],
]

with open("students.csv", "w", newline="", encoding="utf-8") as file:
    csv.writer(file).writerows(students)

with open("students.csv", newline="", encoding="utf-8") as file:
    for row in csv.DictReader(file):
        print(f"{row['Name']}: {row['Grade']}")
Output
Alice: A
Bob: B

pathlib

Build Paths with pathlib

Build Paths with pathlib
from pathlib import Path

# Create path objects
p = Path("data/output.txt")
home = Path.home()
cwd = Path.cwd()

# Path operations
print(p.name)       # output.txt
print(p.stem)       # output
print(p.suffix)     # .txt
print(p.parent)     # data

# Check existence
print(p.exists())
print(p.is_file())
print(p.is_dir())

# Create directories
Path("new_folder/sub").mkdir(parents=True, exist_ok=True)

# Read and write (modern way)
p = Path("hello.txt")
p.write_text("Hello, World!")
content = p.read_text()
print(content)

# List files in directory
for f in Path(".").iterdir():
    print(f)

# Find all Python files recursively
for py_file in Path(".").rglob("*.py"):
    print(py_file)

# Delete file
p.unlink(missing_ok=True)
File handling check

Can You Read and Write Files Safely?

5 checks
  • Use with open() so files close automatically.
  • Choose the correct mode before reading, writing, or appending.
  • Check paths when a file works in one terminal but not another.
  • Specify encoding when text may contain non-ASCII characters.
  • Handle missing files only when the program has a clear recovery path.

File Decisions

0 of 2 checked

Q1. Why is with open(...) preferred for most beginner file work?

Q2. What should you check when a file path fails unexpectedly?

File Bugs That Lose Data

  • Using the wrong path

    Print the current working directory or use pathlib to build a clear file path.
  • Forgetting encoding

    Use encoding="utf-8" for text files unless the file requires something else.
  • Reading huge files at once

    Iterate line by line when the file can be large.

Try this next

Read, Write, and Refactor Files

0 of 3 completed

  1. Read a text file and count non-empty lines.
  2. Create summary.txt with a heading and three calculated values.
  3. Catch FileNotFoundError and print the path that failed.

Questions About File Handling

with open() closes the file automatically, even if an error happens while processing the file.

r reads, w writes and replaces the file, and a appends to the end without deleting existing content.

Relative paths depend on the current working directory. Check where the program is running from.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.