The Python Standard Library

File and directory access

glob

python.org docs

Video tutorial

List of useful glob rules:

import glob

# ? matches any (1) character
# will match apple.py, bpple.py, ...
glob.glob('?pple.py')
# any .py file with 5 characters
glob.glob('?????.py')

# * matches anything, irrespective of length
# any .py file
glob.glob('*.py')
# any file containing .
glob.glob('*.*')

# any of the characters within [] matched
# any .py file whose name starts with a or b or c
glob.glob('[abc]*.py')
# any .py file whose name does not starts with a or b
glob.glob('[!ab]*.py')

glob can be used to recursively search a directory:

# recursively (**) (folder within folder) search dir ('my/dir') to find all .py (*.py) files
# include hidden files 
glob.glob('**/*.py',
          root_dir='my/dir',
          recursive=True,
          include_hidden=True)

glob.iglob: return an iterator which gives the same values as glob.glob without storing them simultaneously

For large directories, this is faster and more memory efficient

globs = glob.iglob('**/*.py',
                   root_dir='my/dir',
                   recursive=True,
                   include_hidden=True)

# get files one by one
print(globs.__next__())
print(globs.__next__())

# or you can iterate over it
for i, file in enumerate(globs):
    print(i, file)

Numerical and mathematical modules

random

https://docs.python.org/3/library/random.html

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.

https://docs.python.org/3/library/random.html#examples

import random
random.random()
random.uniform(0,1)
random.randint(1,6)
random.randint(0,1) # simulate coin toss
fruits = ['apple', 'banana', 'pear', 'nar', 'mango']
random.choice(fruits) # single value
# simulate roulette wheel: 18 reds, 18 blacks, 2 greens
colors = ['red', 'black', 'green']
spin_results = random.choices(population=colors,
                              weights=[18, 18, 2],
                              k=10)
# shuffle a deck of cards
deck = list(range(1, 53))
deck = random.shuffle(deck)
# pick a hand of 5 unique cards
hand = random.sample(population=deck, k=5)