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 Sep 30 2025
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)
Copy to Clipboard
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 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()
Copy to Clipboard
Toggle show comments
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()
Copy to Clipboard
Toggle show comments
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")
Copy to Clipboard
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)
Copy to Clipboard
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")
Copy to Clipboard
Toggle show comments
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
Copy to Clipboard
Toggle show comments
Reading 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 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"}
Copy to Clipboard
Toggle show comments
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)
Copy to Clipboard
Toggle show comments
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"})
Copy to Clipboard














