Draft
edit

Python comes with batteries included. Distributions of Python include modules from the Python Standard Library, which cover a wide range of tools to handle common problems in everyday programming – for example file system access, numerical and mathematical functions, unicode text processing, dealing with dates and calendars, reading / writing multiple data formats, serving web pages, generating random numbers, and a lot more.

Below are a some examples of useful functions provided by standard modules. For more information about each module, follow the links to the official documentation.

os

The os module contains functions that deal with the file system.

import os

os.listdir

Lists the contents of a folder:

os.listdir('/myFolder')

os.walk

Recursively lists the contents of a folder and all its subfolders:

aFolder = '/myFolder'
for path, folders, files in os.walk(aFolder):
    print(path)
    print(folders)
    print(files)
    print('-'*30)

os.getcwd

Returns the folder where the current script is running (current working directory):

>>> os.getcwd()

os.mkdir

Creates a new folder:

newFolder = "/Users/myUsername/Desktop/test"
os.mkdir(newFolder)

os.makedirs

Creates a folder and all parent folders in a given path:

newFolder2 = "/Users/myUsername/Desktop/test2/aSubfolder"
os.makedirs(newFolder2)

os.rename

Renames a folder or file:

oldFile = "/Users/myUsername/Desktop/image.png"
newFile = "/Users/myUsername/Desktop/imageNew.png"
os.rename(oldFile, newFile)

os.remove

Removes a file:

filePath = "/Users/myUsername/Desktop/test3/image.png"
os.remove(filePath)

os.rmdir

Removes an empty folder:

os.rmdir(newFolderName)

To remove a folder and everything that is inside it, use shutil.rmtree (see below).

shutil

The shutil module offers functions to copy and remove collections of files.

import shutil

copytree

Copies a folder and all its contents to a given path, creating missing parent folders.

srcFolder = "/Users/myUsername/Desktop/test1"
dstFolder = "/Users/myUsername/Desktop/backup/test1"
shutil.copytree(srcFolder, dstFolder)

rmtree

Delete a folder and all its contents.

shutil.rmtree(srcFolder)

os.path

The os.path module contains functions for manipulating file and folder names.

os.path.exists

Checks if a file or folder exists, returns a bool:

>>> os.path.exists('/myFile.png')
True
>>> os.path.exists('/myFolder')
False

os.path.basename

Returns the file name for a given path, without the parent folder:

>>> filePath = "/Users/myUsername/Desktop/test3/image.png"
>>> os.path.basename(filePath)
image.png

os.path.dirname

Returns the parent folder of a given file path:

>>> os.path.dirname(filePath)
/Users/myUsername/Desktop/test3

os.path.split

Splits a given file path into parent folder and file name:

folder, fileName = os.path.split(filePath)

os.path.splitext

Splits a file path into root and extension:

>>> os.path.splitext(filePath)
('/Users/myUsername/Desktop/test3/image', '.png')

random

The random module provides functions to generate pseudo-random numbers, etc.

from random import random, randint, choice # ... etc.

random

Returns a random float between 0.0 and 1.0:

>>> for i in range(5):
...     random()
0.1440220412035288
0.6030806336013335
0.23406747728785426
0.12986516342850718
0.5555918432876255

randint

Returns a random int between two given integers:

>>> for i in range(5):
...     randint(10, 70)
17
59
27
40
34

uniform

Returns a random float between two given numbers:

>>> for i in range(5):
...     uniform(0.2, 12)
9.377996146219418
11.67729261822652
9.499059365948389
5.330554497768862
8.164767529218107

choice

Returns one randomly selected item from a given list.

>>> fruits = ['apple', 'orange', 'banana', 'lemon', 'strawberry']
>>> for i in range(5):
...    choice(fruits)
lemon
banana
strawberry
orange
orange

shuffle

Shuffles the items of a given list in place.

for i in range(5):
    shuffle(fruits)
    print(fruits
['apple', 'banana', 'orange', 'lemon', 'strawberry']
['strawberry', 'lemon', 'banana', 'apple', 'orange']
['apple', 'lemon', 'strawberry', 'orange', 'banana']
['apple', 'banana', 'orange', 'lemon', 'strawberry']
['lemon', 'banana', 'apple', 'orange', 'strawberry']

seed

Initializes the random number generator.

This makes is possible to reproduce random values generated inside a script!

from random import random, seed
seed(3)
print(random())

The result of this script will always be:

0.32383276483316237

math

The math module provides several mathematical functions and constants.

from math import *

sqrt

Returns the square root of a number.

>>> sqrt(81)
9.0

floor

Returns the largest integer which is less than or equal to a given number.

>>> floor(4.80)
4

ceil

Returns the smallest integer which is greater than or equal to a given number.

>>> ceil(4.80)
5

pi

The mathematical constant π (pi).

>>> from math import pi
>>> pi
3.141592653589793

sin, cos, tan, etc.

Return the sine, cosine, tangent etc. for a given angle.

The script below shows an example of vector math, using cos and sin to calculate new coordinates from an origin point, angle and distance.

from math import sin, cos

x1, y1 = 100, 100
distance = 800
angle = 60

x2 = x1 + distance * sin(radians(angle))
y2 = y1 + distance * cos(radians(angle))

stroke(1, 0, 0)
line((x1, y1), (x2, y2))

Here’s another example of vector math, using the trigonometric functions hypot (hypothenuse) and atan2 (arc tangent) to calculate the distance and angle between two points.

from math import hypot, atan2

x1, y1 = 100, 100
x2, y2 = 500, 480

distance = hypot(x2 - x1, y2 - y1)
angle = degrees(atan2(y2 - y1, x2 - x1))
  • use radians() to convert angles in degrees to radians
  • use degrees() to convert angles in radians to degrees

string

The string module contains some useful lists of characters:

>>> import string
>>> string.ascii_lowercase
abcdefghijklmnopqrstuvwxyz
>>> string.ascii_uppercase
ABCDEFGHIJKLMNOPQRSTUVWXYZ
>>> string.digits
0123456789
>>> string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

subprocess

json

A module to read and write JSON files.

difflib


Last edited on 06/01/2020