Modules
Updated Oct 28, 2019 ·
Overview
Modules are Python files with a .py extension that contain functions, attributes, and even other modules. Python includes many built-in modules to help us avoid rewriting code.
Common Python Modules
Python has around 200 built-in modules. Some popular ones:
os– Interacts with the operating system, like getting the current directory.collections– Provides advanced data structures.string– Helps with string operations.logging– Logs program events.subprocess– Runs terminal commands from Python.
Importing a Module
To use a module, we import it with the import keyword.
import os
print(type(os)) # Output: <class 'module'>
Finding Module Functions
To see what a module offers, check its documentation or use the help function.
import os
help(os) # Displays a long list of functions and attributes
Using os
Get Current Directory
Use os.getcwd() to find the current working directory.
import os
work_dir = os.getcwd()
print(work_dir)
The output is in quotes, which means the output is a string.
'/home/user/projects'
Changing Directory
Use os.chdir() to move to a different directory.
import os
os.chdir("/home/user/documents")
print(os.getcwd()) # Output: '/home/user/documents'