import glob
# ? matches any (1) character
# will match apple.py, bpple.py, ...
'?pple.py')
glob.glob(# any .py file with 5 characters
'?????.py')
glob.glob(
# * matches anything, irrespective of length
# any .py file
'*.py')
glob.glob(# any file containing .
'*.*')
glob.glob(
# any of the characters within [] matched
# any .py file whose name starts with a or b or c
'[abc]*.py')
glob.glob(# any .py file whose name does not starts with a or b
'[!ab]*.py') glob.glob(
The Python Standard Library
File and directory access
glob
List of useful glob
rules:
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
'**/*.py',
glob.glob(='my/dir',
root_dir=True,
recursive=True) include_hidden
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
= glob.iglob('**/*.py',
globs ='my/dir',
root_dir=True,
recursive=True)
include_hidden
# 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()0,1)
random.uniform(1,6)
random.randint(0,1) # simulate coin toss random.randint(
= ['apple', 'banana', 'pear', 'nar', 'mango']
fruits # single value random.choice(fruits)
# simulate roulette wheel: 18 reds, 18 blacks, 2 greens
= ['red', 'black', 'green']
colors = random.choices(population=colors,
spin_results =[18, 18, 2],
weights=10) k
# shuffle a deck of cards
= list(range(1, 53))
deck = random.shuffle(deck)
deck # pick a hand of 5 unique cards
= random.sample(population=deck, k=5) hand