There are many standard modules. We’ll give a brief of overview of some of these modules below. For reference, here is a full list of standard Python modules.
os module contains many useful functions for dealing with the file system. Here are a few examples:
Lists all the content of a folder:
Recursively list all the contents of a folder:
path = '/my_path/' print(os.walk(path))
Returns the path where the script is running (current working directory):
Create a new folder:
new_folder = u"/Users/yourusername/Desktop/test" os.mkdir(new_folder)
Rename a folder or file:
new_folder2 = u"/Users/yourusername/Desktop/test2" os.rename(new_folder, new_folder2)
Remove a folder:
Remove a file:
os.path module have functions for manipulating file and folder names:
import os.path file = '/my-file.png' path = '/my-folder/'
Check if a file or folder exists:
Returns only the file name, without the folder path where it’s contained:
Returns the containing folder name:
Splits the whole file path as folder and file name:
Splits the file name as file name and extension:
For more information, visit the os.path documentation.
string module offers common string manipulation tools.
import string print(string.lowercase) print(string.uppercase) print(string.digits)
>>> abcdefghijklmnopqrstuvwxyz >>> ABCDEFGHIJKLMNOPQRSTUVWXYZ >>> 0123456789
randint functions from the
from random import random, randint
random() function returns a pseudo-random floating point number between
print("a random number between 0.0 and 1.0:") print(random())
randint() function, on the other hand, returns a pseudo-random number between two integers:
print("a random number between 0 and 4:") print(randint(0, 4)) print("a random number between 10 and 20:") print(randint(10, 20))
Random numbers can be used for randomly selecting between two or more options:
print("choose randomly between A and B, 6 times:") for i in range(6): if random() > 0.5: print("A") else: print("B")
math module has lots of, of course, math operations and constants which are needed for advanced calculations as trigonometry.
Import all functions contained in the
from math import * print(pow(9, 2)) print(sqrt(81)) print(floor(4.80)) print(ceil(4.80))