Course Content
How to Add a Virtual Environment in Python
0/1
Set
0/1
Magic Methods
0/1
Python
About Lesson

The os module in Python provides a way of interacting with the operating system and allows you to perform tasks like file handling, process management, and environment variable manipulation.

Key Functions in os module:

  • File and Directory Operations:
    • os.getcwd(): Returns the current working directory.
    • os.listdir(path): Returns a list of files and directories in the given path.
    • os.mkdir(path): Creates a new directory.
    • os.remove(path): Removes a file.
    • os.rename(src, dst): Renames a file or directory.
  • Environment Variables:
    • os.environ: A dictionary-like object representing the environment variables.
    • os.getenv(name): Gets the value of an environment variable.
  • Process Management:
    • os.system(command): Executes a system command (e.g., run shell commands).
  • Path Operations (using os.path submodule):
    • os.path.join(path1, path2): Joins one or more path components.
    • os.path.exists(path): Checks if a file or directory exists.
    • os.path.abspath(path): Returns the absolute path.

Example:

Python
import os

# Get current working directory
print(os.getcwd())  # Example: /home/user

# List files in a directory
print(os.listdir('.'))  # Lists files in the current directory