Site Tools


import-os

Table of Contents

import os

import os is a Python import that provides functions for interacting with the operating system: file paths, environment variables, process information, and filesystem operations. Use this for cross-platform file handling, reading environment, and running system commands.

Example

# Python
# description: list files in current directory, get home path
 
import os
 
# Print current working directory
print(os.getcwd())
 
# List files in directory
for name in os.listdir('.'):
    print(name)
 
# Access environment variables
home = os.environ.get('HOME')
print(f"Home: {home}")
 
# Get process ID
print(f"Process ID: {os.getpid()}")

Common functions

  • os.getcwd(): current working directory
  • os.chdir(path): change directory
  • os.listdir(path): list directory contents
  • os.makedirs(path): create directories
  • os.remove(path): delete a file
  • os.rmdir(path): delete an empty directory
  • os.rename(src, dst): rename file
  • os.path.exists(path): check if path exists
  • os.path.join(...): join path components (use pathlib for modern code)
  • os.environ: environment variables dictionary
  • os.getenv(key, default): get environment variable
  • os.getpid(): current process ID
  • os.walk(path): walk directory tree recursively
import-os.md · Last modified: by 127.0.0.1