File handling lets your program save data permanently and read it back later. You will use it to load datasets, write logs, save results and read configuration files.
What You Will Learn
- Opening files with modes
- Reading files in different ways
- Writing and appending
- Using with, and working with paths
Prerequisites
File Modes
| Mode | Meaning |
|---|---|
| ‘r’ | Read (default). Error if missing |
| ‘w’ | Write. Creates or overwrites |
| ‘a’ | Append to end. Creates if missing |
| ‘x’ | Create, error if exists |
| ‘b’ | Binary, e.g. ‘rb’ for images |
| ‘+’ | Read and write |
Writing to a File
with open('notes.txt', 'w', encoding='utf-8') as f:
f.write('Line 1\n')
f.write('Line 2\n')
Explanation: with closes the file automatically, even if an error happens. write() does not add a new line, so include \n.
Reading a File
with open('notes.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
Line 1 Line 2
Reading Line by Line
with open('notes.txt', encoding='utf-8') as f:
for line in f:
print(line.strip())
with open('notes.txt', encoding='utf-8') as f:
lines = f.readlines()
print(lines)
Explanation: Looping over the file reads one line at a time, which works even for very large files. strip() removes the newline.
Line 1 Line 2 ['Line 1\n', 'Line 2\n']
Appending
with open('notes.txt', 'a', encoding='utf-8') as f:
f.write('Line 3\n')
Checking and Deleting Files
import os
if os.path.exists('notes.txt'):
print(os.path.getsize('notes.txt'), 'bytes')
os.remove('notes.txt')
Working with Paths
from pathlib import Path
p = Path('data') / 'marks.txt'
p.parent.mkdir(exist_ok=True)
p.write_text('Asha,88\n', encoding='utf-8')
print(p.read_text(encoding='utf-8'))
Explanation: pathlib builds paths that work on both Windows and Linux.
Asha,88
Reading CSV and JSON
import csv, json
with open('marks.csv', newline='', encoding='utf-8') as f:
for row in csv.reader(f):
print(row)
with open('config.json', encoding='utf-8') as f:
config = json.load(f)
Explanation: Use the csv and json modules instead of splitting text by hand. For data analysis, Pandas read_csv() is even easier.
Common Errors
| Problem | Cause and fix |
|---|---|
FileNotFoundError |
Wrong name or the script runs from a different folder. Print os.getcwd() to check. |
UnicodeDecodeError |
Pass encoding='utf-8' (or the file’s real encoding). |
| File content disappeared | Mode ‘w’ overwrites. Use ‘a’ to add. |
Practice Exercises
- Count lines and words in a text file.
- Copy one file to another.
- Save a list of student marks and read it back to find the average.
Interview Questions
Q: Why use with open()?
It closes the file automatically, even on errors.
Q: Difference between w and a?
w overwrites; a appends.
Summary
Open files with with open(path, mode, encoding=…), read with read()/loops, write with w or a, and use pathlib, csv and json for real projects.
Next: Python Exceptions · Python Modules
Machine Learning Tutorials, Courses and Certifications