File Handling
Python - A Quick Start for existing Programers
2 min read
This section is 2 min read, full guide is 44 min read
Published Sep 16 2025, updated Aug 17 2026
21
Show sections list
0
Log in to enable the "Like" button
0
Guide comments
0
Log in to enable the "Save" button
Respond to this guide
Guide Sections
Guide Comments
Python
Python allows you to read from, write to, and manipulate files easily using built-in functions.
- Open a file →
open(filename, mode) - Read →
read(),readline(),readlines() - Write / Append →
write(),writelines() - Always close files →
f.close()orwithstatement - Binary vs text →
'b'mode for non-text files - File management →
osmodule 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., |
't' | Text mode (default, can be omitted). |
'+' | Update (read and write, e.g., |
Reading from Files
f = open("example.txt", "r")# Read entire contentcontent = f.read()# Read line by linefor line in f: print(line.strip())# Read a single lineline = f.readline()# Read all lines as a listlines = 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 existsos.path.exists("example.txt")# Delete a fileos.remove("example.txt")# Rename a fileos.rename("old.txt", "new.txt")# Get file sizeos.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 filewith open("data.csv", "r", newline="") as f: reader = csv.reader(f) for row in reader: print(row) # Each row is a list of stringsReading csv with Headers (DictReader)
DictReaderautomatically uses the first row as field names.- Easier if you want to access by column name instead of index.
import csvwith 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 rowsrows = [ ["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"})