os
Working with the operating system: paths, directories, files, and environment variables.
Example
#import os
path = os.path.join("courses", "python", "lesson_01.py")
print(path)
print(os.path.basename(path))
print(os.path.dirname(path))
print(os.path.splitext(path)[1])
print(os.path.exists("no_such_file.txt"))The result is for Linux and macOS. On Windows, os.path.join() will use backslashes: courses\python\lesson_01.py.
Definition and usage
#The os module lets a program use operating system features so that the same code works on Windows, Linux, and macOS. It has functions for listing directories (listdir()), creating and removing directories (makedirs(), rmdir()), deleting and renaming files (remove(), rename()), and reading the current directory (getcwd()).
The os.path submodule is for operations on paths written as strings. join() combines the parts of a path with the separator that suits the system, basename() and dirname() separate the file name from the directory, splitext() cuts off the extension, and exists() checks whether a file exists.
The os.environ dictionary holds environment variables, where configuration and secrets are kept, for example a database address. For paths alone, the pathlib module is more convenient in new code, because it treats a path as an object.
Syntax
#import os
os.path.join(part, β¦)
os.path.exists(path)
os.listdir(directory)
os.makedirs(directory, exist_ok=True)
os.environ.get(name, default)More examples
#import os
os.makedirs("project/assets", exist_ok=True)
with open("project/plan.txt", "w", encoding="utf-8") as file:
file.write("Learning Python")
print(sorted(os.listdir("project")))
os.rename("project/plan.txt", "project/study_plan.txt")
print(sorted(os.listdir("project")))
os.remove("project/study_plan.txt")
print(sorted(os.listdir("project")))The result assumes the project directory did not exist before. Thanks to exist_ok=True, running it again will not raise an error.
import os
mode = os.environ.get("CODEWORLDS_MODE", "development")
debug = os.getenv("CODEWORLDS_DEBUG") == "1"
print(mode, debug)The result when the CODEWORLDS_MODE and CODEWORLDS_DEBUG variables are not set. In a Linux or macOS terminal you can set them like this: CODEWORLDS_DEBUG=1 python app.py.
Good practices
#- Do not glue paths together with
+and slashes.os.path.join()orpathlibwill insert the separator that suits the system. - Keep passwords and API keys in environment variables, not in code, and read them with
os.environ.get(). os.remove()deletes a file immediately and permanently, bypassing the trash.
Related entries
#- os vs pathlibos represents paths as plain strings and operates on them with functions, while pathlib represents a path as a Path object with methods and the / operator.
- pathlibPaths as objects: joining with the / operator, reading the parts of a path, and working with files.
- sysAccess to the interpreter: command-line arguments, ending the program, the Python version, and streams.
- open()Opens a file for reading or writing and returns a file object.
- withA context manager: automatic setup and cleanup of resources.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.