File Handling

Python - A Quick Start for existing Programers

2 min read

Published Sep 16 2025, updated Sep 30 2025


21
0
0
0

Python

Python allows you to read from, write to, and manipulate files easily using built-in functions.

  • Open a fileopen(filename, mode)
  • Readread(), readline(), readlines()
  • Write / Appendwrite(), writelines()
  • Always close filesf.close() or with statement
  • Binary vs text'b' mode for non-text files
  • File managementos module functions



Opening Files

file = open("filename.txt", mode)

Modes:

Mode

Description

'r'

Read (default). File must exist.

'w'

Write. Creates a new file or overwrites.

'a'

Append. Adds content to the end of file.

'x'

Exclusive creation. Fails if file exists.

'b'

Binary mode (e.g., 'rb', 'wb').

't'

Text mode (default, can be omitted).

'+'

Update (read and write, e.g., 'r+').




Reading from Files

f = open("example.txt", "r")

# Read entire content
content = f.read()

# Read line by line
for line in f:
    print(line.strip())

# Read a single line
line = f.readline()

# Read all lines as a list
lines = f.readlines()

f.close()




Writing to Files

# Write (overwrites)
f = open("example.txt", "w")
f.write("Hello World\n")
f.writelines(["Line 1\n", "Line 2\n"])
f.close()

# Append (adds to the end)
f = open("example.txt", "a")
f.write("New line at the end\n")
f.close()




Using with Statement (Recommended)

  • Automatically closes the file, even if an error occurs.
with open("example.txt", "r") as f:
    content = f.read()

with open("example.txt", "a") as f:
    f.write("Appending safely!\n")




Binary Files

  • Open with 'rb' or 'wb'.
  • Useful for images, audio, or any non-text data.
with open("image.png", "rb") as f:
    data = f.read()

with open("copy.png", "wb") as f:
    f.write(data)




Other Useful File Operations

import os

# Check if file exists
os.path.exists("example.txt")

# Delete a file
os.remove("example.txt")

# Rename a file
os.rename("old.txt", "new.txt")

# Get file size
os.path.getsize("example.txt")




Using the csv module

  • csv.reader → reads rows as lists.
  • You may need to handle headers manually (next(reader) to skip).
import csv

# Reading a CSV file
with open("data.csv", "r", newline="") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
        # Each row is a list of strings




Reading csv with Headers (DictReader)

  • DictReader automatically uses the first row as field names.
  • Easier if you want to access by column name instead of index.
import csv

with open("data.csv", "r", newline="") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)
        # Each row is a dict: {"column": "value"}




Writing CSV Files

import csv

# Writing rows
rows = [
    ["Name", "Age", "City"],
    ["Alice", 30, "London"],
    ["Bob", 25, "New York"]
]

with open("output.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(rows)




Writing CSV files with Dicts

with open("output.csv", "w", newline="") as f:
    fieldnames = ["Name", "Age", "City"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)

    writer.writeheader()
    writer.writerow({"Name": "Alice", "Age": 30, "City": "London"})
    writer.writerow({"Name": "Bob", "Age": 25, "City": "New York"})

Products from our shop

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet - Print at Home Designs

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Mouse Mat

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Travel Mug

Docker Cheat Sheet Mug

Docker Cheat Sheet Mug

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet - Print at Home Designs

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Mouse Mat

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Travel Mug

Vim Cheat Sheet Mug

Vim Cheat Sheet Mug

SimpleSteps.guide branded Travel Mug

SimpleSteps.guide branded Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript - Travel Mug

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Dark

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Embroidered T-Shirt - Light

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - White

Developer Excuse Javascript Mug - Black

Developer Excuse Javascript Mug - Black

SimpleSteps.guide branded stainless steel water bottle

SimpleSteps.guide branded stainless steel water bottle

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Light

Developer Excuse Javascript Hoodie - Dark

Developer Excuse Javascript Hoodie - Dark

© 2025 SimpleSteps.guide
AboutFAQPoliciesContact