Intermediate Python for Developers
George Boorman
Curriculum Manager, DataCamp
Modules are Python scripts
.py
Python comes with several modules
Help us avoid writing code that already exists!
os
- for interpreting and interacting with your operating systemcollections
- advanced data structure types and functionsstring
- performing string operationslogging
- to log information when testing or running softwaresubprocess
- to run terminal commands within a Python file
# List all files in a directory
ls
# General syntax
import <module_name>
# Import the os module
import os
# Check the type
type(os)
<class 'module'>
# Call help()
# Warning - will return a very large output!
help(os)
Help on module os:
NAME
os - OS routines for NT or Posix depending on what system we're on.
MODULE REFERENCE
https://docs.python.org/3.10/library/os.html
# Using an os function
os.getcwd()
'/home/georgeboorman/intermediate_python_for_developers'
# Assign to a variable
work_dir = os.getcwd()
# Changing directory
os.chdir("/home/georgeboorman")
# Check the current directory
os.getcwd()
'/home/georgeboorman'
# Confirm work_dir has not changed
work_dir
'/home/georgeboorman/intermediate_python_for_developers'
# Get the local environment
os.environ
environ{'PATH': '/usr/local/bin',
'TERM': 'xterm',
'HOSTNAME': '097a0fe4-d6ce-4325-a6e2-1d0ce2800c2b',
'TZ': 'Europe/Brussels',
'PYTHONWARNINGS': 'ignore',
'LANG': 'en_US.UTF-8'
...}
Importing a whole module can require a lot of memory
Can import a specific function from a module
# Import a function from a module
from os import chdir
# Import multiple functions from a module from os import chdir, getcwd
# No need to include os. getcwd()
'/home/georgeboorman'
os
module so Python won't understandIntermediate Python for Developers