Python File Handling Examples
Short, runnable programs that show python file handling in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python File Handling lesson.
1Count lines, words and characters
read() returns the whole file as one string, so ordinary string methods work on it.
with open("story.txt", "w") as f:
f.write("Python is fun.\nFiles keep data safe.\nPython reads files fast.\n")
with open("story.txt") as f:
content = f.read()
print("Characters:", len(content))
print("Lines:", content.count("\n"))
print("Words:", len(content.split()))
print("'Python' appears", content.count("Python"), "times")Expected outputCharacters: 62
Lines: 3
Words: 11
'Python' appears 2 times
2Add up numbers stored in a file
Each line is a string such as "12.50\n". float() ignores the surrounding whitespace, so you can convert it directly.
with open("expenses.txt", "w") as f:
f.write("12.50\n8.25\n30.00\n")
total = 0
with open("expenses.txt") as f:
for line in f:
total += float(line)
print(f"Total spent: {total:.2f}")Expected outputTotal spent: 50.75
3Fall back to a default when the file is missing
A function that loads saved settings can return sensible defaults the first time, before any file exists.
def load_theme(filename):
try:
with open(filename) as f:
return f.read().strip()
except FileNotFoundError:
return "light"
print("Before saving:", load_theme("theme.txt"))
with open("theme.txt", "w") as f:
f.write("dark\n")
print("After saving:", load_theme("theme.txt"))Expected outputBefore saving: light
After saving: dark
4Write with print(..., file=f)
print() can send its output to a file instead of the screen. Unlike write(), it adds the newline and converts numbers for you.
guests = ["Asha", "Ben", "Chen"]
with open("guests.txt", "w") as f:
for number, name in enumerate(guests, start=1):
print(number, name, file=f)
with open("guests.txt") as f:
print(f.read(), end="")Expected output1 Asha
2 Ben
3 Chen
Practise next
Python File Handling exercises → Back to the lesson
Python with Statement examplesPython pathlib examplesWorking with JSON in Python examplesPython CSV Files examples