os

Working with the operating system: paths, directories, files, and environment variables.

On this page

Example

#
Python
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"))
Resultsaved result, you can check it
courses/python/lesson_01.py
lesson_01.py
courses/python
.py
False

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

#
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

#
Directories and files
Python
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")))
Resultsaved result, you can check it
['assets', 'plan.txt']
['assets', 'study_plan.txt']
['assets']

The result assumes the project directory did not exist before. Thanks to exist_ok=True, running it again will not raise an error.

Environment variables
Python
import os

mode = os.environ.get("CODEWORLDS_MODE", "development")
debug = os.getenv("CODEWORLDS_DEBUG") == "1"

print(mode, debug)
Resultsaved result, you can check it
development False

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() or pathlib will 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

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.