12.5Standard Library Modules: Attributes, os and sys
Covers IGNOU MCS-201 §12.6
The standard library is the large collection of modules that comes with every Python installation: files, dates, maths, networking, JSON, databases and much more. This section looks at features shared by all modules and at two system modules, os and sys.
Attributes and tools for every module
Tool
What it gives
help(module)
Documentation of the module; help("modules") lists the installed modules
dir(module)
A list of the names (functions, variables, classes) defined in the module
module.__name__
The module’s name ("__main__" for the running script)
module.__file__
The path of the file the module was loaded from (absent for modules built into the interpreter, such as sys)
module.__doc__
The module’s docstring, or None
The os module
os lets a program work with the operating system: folders, paths, environment variables.
Function
Purpose
os.getcwd()
Current working directory
os.chdir(path)
Change the current working directory
os.mkdir(path), os.makedirs(path)
Create a folder (makedirs also creates missing parent folders)
os.rmdir(path)
Remove an empty folder
os.listdir(path=".")
Names of the entries in a folder
os.environ
Dictionary-like access to environment variables
os.path.join(a, b)
Join path parts with the right separator for the system
The sys module
sys gives access to the Python interpreter itself.
Name
Purpose
sys.argv
List of command-line arguments; sys.argv[0] is the script name
sys.path
Module search path
sys.version, sys.version_info
Python version as a string / as a tuple-like object
sys.platform
Operating system identifier, e.g. "linux", "darwin", "win32"
sys.getsizeof(obj)
Memory used by an object, in bytes
sys.maxsize
Largest index a container can have on this system
sys.exit(code)
End the program (0 means success)
Key takeaways
The standard library is installed with Python; import modules before use.
help, dir, __name__, __file__, __doc__ work for every module.
sys.maxsize limits container sizes, not integer values.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a script that prints the names of all .py files in the current folder in alphabetical order.
Show worked answer
import os, then for name in sorted(os.listdir(".")): if name.endswith(".py"): print(name). os.listdir(".") returns the entries of the current folder in no guaranteed order, sorted() puts them in alphabetical order, and endswith(".py") keeps only Python files.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/modules-and-packages/standard-library-modules-attributes-os-and-sys/ to read this page.