Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 17 of 22 · 4 min read

Python standard library power tools

Python standard library notes: datetime parsing and formatting, pathlib and shutil, Counter and defaultdict, and regular expressions with re.

The standard library

Python comes with a large set of modules ready to import, nothing to install. People call this "batteries included". This topic covers the ones you will use most in real projects.

datetime: parse, format and calculate with dates

from datetime import datetime, date, timedelta

d = datetime.strptime("29-10-2026", "%d-%m-%Y")    # parse: text to a date
print(d.strftime("%A, %d %B %Y"))                  # format: Thursday, 29 October 2026

due = date.today() + timedelta(days=15)            # add days
left = (date(2027, 3, 1) - date.today()).days      # difference in days
CodeMeaningExample
%dday, 2 digits29
%mmonth number10
%B / %bmonth name, full / shortOctober / Oct
%Y4-digit year2026
%Aweekday nameThursday
%H:%M24-hour time17:05
%I:%M %p12-hour time05:05 PM

Remember: strptime = string *parse* to time; strftime = string *format* from time.

pathlib: work with files and folders

from pathlib import Path

folder = Path("reports")
folder.mkdir(exist_ok=True)                 # create it if it does not exist
file = folder / "march.txt"                 # '/' joins path parts
file.write_text("Total: 500", encoding="utf-8")
print(file.exists(), file.name, file.suffix)   # True march.txt .txt

for p in Path(".").glob("*.csv"):           # every CSV in the current folder
    print(p.name, p.stat().st_size, "bytes")

shutil: copy, move and back up

import shutil
shutil.copy("marks.csv", "backup/marks.csv")      # copy a file
shutil.move("old.txt", "archive/old.txt")         # move or rename
shutil.make_archive("backup", "zip", "reports")   # zip a whole folder

A downloads organiser combines both: loop over files with Path.glob, look at each suffix, and shutil.move the file into a folder for its type.

collections: smarter containers

Counter: count anything

from collections import Counter
votes = ["Asha", "Ravi", "Asha", "Meena", "Asha"]
c = Counter(votes)
print(c["Asha"])            # 3
print(c.most_common(2))     # [('Asha', 3), ('Ravi', 1)]

defaultdict: no KeyError for new keys

from collections import defaultdict
by_class = defaultdict(list)
for name, cls in [("Asha", 10), ("Ravi", 9), ("Meena", 10)]:
    by_class[cls].append(name)      # a missing key starts as an empty list
print(dict(by_class))               # {10: ['Asha', 'Meena'], 9: ['Ravi']}

namedtuple and deque

from collections import namedtuple, deque
Point = namedtuple("Point", "lat lon")
ranchi = Point(23.34, 85.31)
print(ranchi.lat)                   # read fields by name

queue = deque(["A", "B"])
queue.append("C")                   # join at the back
print(queue.popleft())              # A -- fast removal from the front

Regular expressions: find patterns in text

A regular expression (regex) describes a pattern of text, such as "10 digits" or "an email address".

PatternMatches
\done digit
\wa letter, digit or underscore
\sa space, tab or new line
.any character
[A-Z]one capital letter
+one or more of the previous
*zero or more
{3} / {2,4}exactly 3 / between 2 and 4
^ and $start and end of the text

Using re: search, findall, fullmatch, sub

import re

text = "Call 9876543210 or 9123456780"
print(re.findall(r"\d{10}", text))          # both numbers, as a list

m = re.search(r"\d{10}", text)              # the first match, or None
if m:
    print(m.group())

pan = "ABCDE1234F"
print(bool(re.fullmatch(r"[A-Z]{5}\d{4}[A-Z]", pan)))   # True: the whole text must match

print(re.sub(r"\s+", " ", "too    many   spaces"))      # 'too many spaces'

Always write patterns as raw strings (r"..."), so backslashes reach re unchanged.

FunctionUse it to
re.searchfind the first match anywhere
re.findallget every match as a list
re.fullmatchcheck that the whole text fits the pattern (validation)
re.subreplace every match

Common mistakes

  • Mixing up strptime and strftime.
  • Using re.search to validate input: it accepts extra text around the match. Use re.fullmatch.
  • Forgetting the r before a regex string.
  • Joining paths with + and backslashes by hand instead of Path(...) / "name".

Key points

  • datetime parses with strptime, formats with strftime, and adds days with timedelta.
  • pathlib.Path and shutil handle files and folders.
  • Counter counts; defaultdict gives new keys a starting value.
  • re.findall, re.fullmatch and re.sub find, validate and replace text patterns.

Practice questions

1. Convert "2026-12-25" into "25 Dec 2026".
from datetime import datetime
d = datetime.strptime("2026-12-25", "%Y-%m-%d")
print(d.strftime("%d %b %Y"))
2. Find the three most common words in a sentence.
from collections import Counter
print(Counter(sentence.lower().split()).most_common(3))
3. Write a regex that checks for a 6-digit Indian PIN code.

re.fullmatch(r"\d{6}", pin) (or r"[1-9]\d{5}", since PIN codes do not start with 0).

4. List the names of all .jpg files in a folder.
from pathlib import Path
print([p.name for p in Path("photos").glob("*.jpg")])
5. What is the difference between re.search and re.fullmatch?

search finds the pattern anywhere in the text; fullmatch succeeds only if the entire text matches.