Files
Always open files with with: it closes the file for you, even if an error happens. The mode is "r" (read), "w" (write, erases first), "a" (append) or "x" (create, fail if it exists).
open(), write(), read()
Write a file and read it back. Add encoding="utf-8" for non-English text.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("line one\n")
f.write("line two\n")
with open("notes.txt", encoding="utf-8") as f:
text = f.read()
print(repr(text))
Output:
'line one\nline two\n'
readline(), readlines() and looping
Reading line by line is memory friendly for big files.
with open("data.txt", "w") as f:
f.write("a\nb\nc\n")
with open("data.txt") as f:
for line in f:
print(line.strip())
with open("data.txt") as f:
print(f.readlines())
Output:
a
b
c
['a\n', 'b\n', 'c\n']
append mode and writelines()
"a" adds to the end without erasing.
with open("log.txt", "w") as f:
f.writelines(["start\n", "middle\n"])
with open("log.txt", "a") as f:
f.write("end\n")
print(open("log.txt").read().split())
Output:
['start', 'middle', 'end']
pathlib.Path
A modern way to work with paths and files.
from pathlib import Path
p = Path("report.final.txt")
p.write_text("hello")
print(p.read_text())
print(p.suffix, p.stem, p.exists())
p.unlink()
print(p.exists())
Output:
hello
.txt report.final True
False
os and shutil
Check, list, create and remove files and folders (example not run: it depends on your folders).
import os
print(os.getcwd()) # current folder
print(os.listdir(".")) # names in a folder
print(os.path.exists("data.txt"))
os.makedirs("backup", exist_ok=True)
CSV
csv module
Read and write spreadsheet-style files correctly (quotes and commas inside values).
import csv
rows = [["name", "marks"], ["Ram", 80], ["Sita", 92]]
with open("marks.csv", "w", newline="") as f:
csv.writer(f).writerows(rows)
with open("marks.csv", newline="") as f:
for row in csv.DictReader(f):
print(row["name"], int(row["marks"]) + 5)
Output:
Ram 85
Sita 97
JSON
json.dumps(obj) and json.loads(text)
Convert Python data to JSON text and back. JSON turns tuples into lists and None into null.
import json
data = {"name": "Sita", "marks": [80, 92], "passed": True, "note": None}
text = json.dumps(data)
print(text)
print(json.loads(text)["marks"][1])
Output:
{"name": "Sita", "marks": [80, 92], "passed": true, "note": null}
92
indent, sort_keys, ensure_ascii
Make JSON readable, ordered, or keep non-English letters as they are.
import json
print(json.dumps({"b": 1, "a": "नेपाल"}, indent=2, sort_keys=True, ensure_ascii=False))
Output:
{
"a": "नेपाल",
"b": 1
}
json.dump(obj, file) and json.load(file)
The same, straight to and from a file.
import json
with open("s.json", "w") as f:
json.dump({"x": [1, 2]}, f)
with open("s.json") as f:
print(json.load(f))
Output:
{'x': [1, 2]}
Dates and times
datetime.date and timedelta
Dates without a time; add or subtract days with timedelta.
from datetime import date, timedelta
d = date(2026, 10, 4)
print(d)
print(d + timedelta(days=30))
print(d.weekday(), d.strftime("%A"))
print((date(2026, 12, 25) - d).days)
Output:
2026-10-04
2026-11-03
6 Sunday
82
datetime.datetime
A date with a time.
from datetime import datetime
t = datetime(2026, 10, 4, 14, 30)
print(t)
print(t.hour, t.minute)
print(t.isoformat())
Output:
2026-10-04 14:30:00
14 30
2026-10-04T14:30:00
strftime() and strptime()
Turn a date into text with a format, and parse text back into a date. Common codes: %Y year, %m month, %d day, %H:%M time, %B month name.
from datetime import datetime
t = datetime(2026, 10, 4, 14, 30)
print(t.strftime("%d %B %Y, %H:%M"))
print(datetime.strptime("2026-03-15", "%Y-%m-%d").date())
Output:
04 October 2026, 14:30
2026-03-15
Today and now
These change every second, so the example is shown but not run.
from datetime import date, datetime
print(date.today())
print(datetime.now())
Nepali (Bikram Sambat) dates are not built into Python. Convert BS to AD with a tested library or a conversion table, and store dates internally as normal AD dates.
Try it yourself
- Write a program that appends a line with the current date to a log file each time it runs.
- Load a JSON file of students, add a field to each, and save it back.
- Work out how many days are left until your next birthday.
Next lesson: collections, itertools and random.

Comments
Loading comments…