[Ch 9] Everything About Python Standard Library from the Official Documentation

박주원
July 26, 2025

[Ch 9] Everything About Python Standard Library from the Official Documentation

Use Original Cover Image
Type
Post
Children
Language
en
Tags
Python
shutil
argparse
Regex
math
urllib
random
statistics
smtplib
datetime
doctest
unittest
Authors
박주원
Published
July 26, 2025
Overview
This document is a more easily understandable summary of the contents of 10. Brief Tour of Standard Library in the official Python v3.13 Tutorial.
 

1. Operating System Interface

1.1 os Module

import os print(os.getcwd()) os.chdir('/server/accesslogs') os.system('mkdir today')
page icon
C:\\path\\to\\folder\\repository
The os module provides various functions for interacting with the operating system.
 
When importing the module, be sure to use the import os format rather than from os import *.
This is to prevent conflicts between Python's built-in open() function and the os module's os.open() function.
 
import os print(dir(os)) print(help(os))
page icon
['DirEntry', 'EX_OK', 'F_OK', 'GenericAlias', ...] Help on module os: NAME os - OS routines for NT or Posix depending on what system we're on. ...
You can also use the dir or help functions to get detailed information about a module.
dir returns a list of all the content that the module exports, and help creates a manual for the module based on its docstring.
 

1.2 shutil Module

import shutil shutil.copyfile('data.db', 'archive.db') shutil.move('/build/executables', 'installdir')
The shutil module provides functions for easily controlling files and folders.
 

2. File Wildcards

import glob print(glob.glob('*.py'))
page icon
['code1.py', 'code2.py', 'tmp.py']
The glob module provides a function for finding files using wildcards.
 

3. Command-Line Arguments

3.1 sys.argv

# demo.py file import sys print(sys.argv)
page icon
PS C:\\path\\to\\folder> python demo.py 1 Hello True ['demo.py', '1', 'Hello', 'True']
The sys module allows you to receive values passed as arguments when running a Python file through sys.argv.
 

3.2 argparse Module

# demo.py file import argparse parser = argparse.ArgumentParser( prog='top', description='Show top lines from each file') parser.add_argument('filenames', nargs='+') parser.add_argument('-l', '--lines', type=int, default=10) args = parser.parse_args() print(args)
page icon
PS C:\\path\\to\\folder> python demo.py usage: top [-h] [-l LINES] filenames [filenames ...] top: error: the following arguments are required: filenames
page icon
PS C:\\path\\to\\folder> python demo.py file.txt -l 3 Namespace(filenames=['file.txt'], lines=3)
The argparse module allows for more advanced handling of command-line arguments for Python files.
 

4. Error Messages and Program Termination

import sys sys.stderr.write('An error has occurred.') sys.exit(1)
page icon
An error has occurred.
The sys module also allows you to write error messages to stderr.
The sys.exit function stops the execution of the program and can be assigned a specific exit code.
An exit code of 1 indicates an abnormal termination.
 

5. Regex Matching

import re print(re.findall(r'\\bf[a-z]*', 'which foot or hand fell fastest')) print(re.sub(r'(\\b[a-z]+) \\1', r'\\1', 'cat in the the hat')) print('tea for too'.replace('too', 'two'))
page icon
['foot', 'fell', 'fastest'] cat in the hat tea for two
By using the re module, you can perform string matching, searching, and substitution with regular expressions.
 

6. Mathematics

6.1 math Module

import math print(math.cos(math.pi / 4)) print(math.log(1024, 2))
page icon
0.7071067811865476 10.0
The math module supports basic mathematical functions and constants.
The supported functions and constants follow the C language standard.
 

6.2 random Module

import random print(random.choice(['apple', 'pear', 'banana'])) print(random.sample(range(100), 10)) print(random.random()) print(random.randrange(6))
page icon
apple [14, 40, 78, 99, 21, 85, 18, 64, 54, 27] 0.9291587367817131 4
page icon
banana [81, 44, 9, 88, 87, 17, 90, 24, 29, 66] 0.5187855811434525 3
The random module supports a wide range of things related to randomness and probability.
Unlike C, it does not require initial seed initialization to use random numbers.
 

6.3 statistics Module

import statistics data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] print(statistics.mean(data)) print(statistics.median(data)) print(statistics.variance(data))
page icon
1.6071428571428572 1.25 1.3720238095238095
The statistics module supports many things related to statistics.
 

7. Internet Access

7.1 urllib Package

from urllib.request import urlopen with urlopen('https://timeapi.io/api/time/current/zone?timeZone=Etc%2FUTC') as response: data = response.read() data = data.decode('utf-8') print(data)
page icon
{"year":2025,"month":7,"day":26,"hour":8,"minute":27,"seconds":47,"milliSeconds":397,"dateTime":"2025-07-26T08:27:47.3977202","date":"07/26/2025","time":"08:27","timeZone":"Etc/UTC","dayOfWeek":"Saturday","dstActive":false}
The urllib package contains several modules related to URLs.
The urllib.request module allows you to make URL requests, mainly HTTP requests.
 

7.2 smtplib Module

import smtplib server = smtplib.SMTP('localhost') server.sendmail('soothsayer@example.org', 'jcaesar@example.org', """To: jcaesar@example.org From: soothsayer@example.org Beware the Ides of March. """ ) server.quit()
The smptlib module allows you to create an SMTP client and send emails.
 

8. Dates and Times

from datetime import date now = date.today() print(now) print(now.strftime("%m-%d-%y. %d %b %Y is a %A on the %d day of %B.")) birthday = date(1964, 7, 31) age = now - birthday print(age.days)
page icon
2025-07-24 07-24-25. 24 Jul 2025 is a Thursday on the 24 day of July. 22273
The datetime module supports various functions related to dates and times.
In addition to dates and times, it also supports date output formatting and timezones.
 

9. Data Compression

import zlib s = b'witch which has which witches wrist watch' print(len(s)) t = zlib.compress(s) print(len(t)) print(zlib.decompress(t)) print(zlib.crc32(s))
page icon
41 37 b'witch which has which witches wrist watch' 226805979
Python supports modules such as zlib, gzip, bz2, lzma, zipfile, and tarfile for data compression.
 

10. Performance Measurement

from timeit import Timer print(Timer('t=a; a=b; b=t', 'a=1; b=2').timeit()) print(Timer('a,b = b,a', 'a=1; b=2').timeit())
page icon
0.017941600002814084 0.009880399997200584
When you need to measure the performance of a program in Python, you can use a module like timeit.
The timeit module allows you to measure the time it takes to execute code written as a string.
For larger code blocks, you can use modules like profile and pstats.
 

11. Testing

11.1 doctest Module

def average(values): """Computes the arithmetic mean of a list of numbers. >>> print(average([20, 30, 70])) 40.0 """ return sum(values) / len(values) import doctest print(doctest.testmod())
page icon
TestResults(failed=0, attempted=1)
The doctest module allows you to easily run tests and see the results based on the program's docstring.
 

11.2 unittest

import unittest def average(values): return sum(values) / len(values) class TestStatisticalFunctions(unittest.TestCase): def test_average(self): self.assertEqual(average([20, 30, 70]), 40.0) self.assertEqual(round(average([1, 5, 7]), 1), 4.3) with self.assertRaises(ZeroDivisionError): average([]) with self.assertRaises(TypeError): average(20, 30, 70) unittest.main()
page icon
. ---------------------------------------------------------------------- Ran 1 test in 0.000s OK
The unittest module provides tools for conducting unit tests.
 

12. “Batteries Included” Philosophy

Python promotes the “Batteries Included” philosophy as the motto for its standard modules.
“Batteries Included” means that most tasks can be performed with only the standard modules, without the need for additional modules.
Although we have briefly looked at various standard modules in this document, Python supports over 200 standard modules.
As such, Python follows the “Batteries Included” philosophy of minimizing the use of external packages by supporting the vast majority of functionalities as built-in modules.
 

Reference

[1] Python Software Foundation. "10. Brief Tour of the Standard Library" The Python Tutorial, version 3.13, Python Software Foundation, 2024, https://docs.python.org/3.13/tutorial/stdlib Accessed 26 July 2025.