Exploring the os Library With Python

enghaon

≀Paulo Portela

Posted on February 26, 2024

Exploring the os Library With Python

Introduction

The os library in Python serves as a cornerstone for interacting with the operating system, providing functions for file and directory manipulation, process management, environment variables, and more. This chapter delves into the myriad capabilities of the os module and demonstrates its utility through practical examples.

Topics

  • File and directory operations
  • Process management
  • Environment variables manipulation

File and Directory Operations

The os module offers a plethora of functions for performing file and directory operations, facilitating tasks such as file creation, deletion, renaming, and directory navigation.

Checks for the existence of a file

import os

# Check if a file exists
file_path = "example.txt"
if os.path.exists(file_path):
    print("File exists.")
else:
    print("File does not exist.")
Enter fullscreen mode Exit fullscreen mode

Output:

File does not exist.
Enter fullscreen mode Exit fullscreen mode

Creates a new folder

import os

# Create a directory
directory_path = "example_directory"
os.mkdir(path=directory_path)
print("Directory created.")
Enter fullscreen mode Exit fullscreen mode

Output:

Directory created.
Enter fullscreen mode Exit fullscreen mode

Renames a file

import os

# Rename a file
file_path = "example.txt"
new_file_path = "new_example.txt"
os.rename(file_path, new_file_path)
print("File renamed.")
Enter fullscreen mode Exit fullscreen mode

Output:

File renamed.
Enter fullscreen mode Exit fullscreen mode

Lists the files found within a directory

import os

# List files in a directory
directory_path = "example_directory"
files = os.listdir(path=directory_path)
print("Files in directory:", files)
Enter fullscreen mode Exit fullscreen mode

Output:

Files in directory: ['example.txt']
Enter fullscreen mode Exit fullscreen mode

Deletes a directory as long as it is empty

import os

# Remove a directory
directory_path = "example_directory"
os.rmdir(path=directory_path)
print("Directory removed.")
Enter fullscreen mode Exit fullscreen mode

Output:

Directory removed.
Enter fullscreen mode Exit fullscreen mode

Process Management

With the os module, you can interact with processes, including launching new processes, obtaining process IDs, and managing process attributes.

import os

# Launch a new process
os.system("ls -l")

# Get the process ID of the current process
pid = os.getpid()
print("Process ID:", pid)

# Get the parent process ID
ppid = os.getppid()
print("Parent Process ID:", ppid)
Enter fullscreen mode Exit fullscreen mode

Output:

total 96
-rw-r--r--@ 1 tlayach  staff      0 Feb 26 00:03 example.txt
Enter fullscreen mode Exit fullscreen mode

Environment Variables Manipulation

The os module enables manipulation of environment variables, allowing you to retrieve, set, and unset environment variables.

import os

# Get value of an environment variable
python_path = os.getenv("PYTHONPATH")
print("PYTHONPATH:", python_path)

# Set an environment variable
os.environ["NEW_VARIABLE"] = "new_value"
print("NEW_VARIABLE set.")

# Unset an environment variable
os.environ.pop("NEW_VARIABLE", None)
print("NEW_VARIABLE unset.")
Enter fullscreen mode Exit fullscreen mode

Output:

PYTHONPATH: /Users/...
NEW_VARIABLE set.
NEW_VARIABLE unset.
Enter fullscreen mode Exit fullscreen mode

Conclusion

The os library in Python serves as a versatile toolkit for interacting with the operating system, empowering developers to perform a wide range of file and directory operations, manage processes, and manipulate environment variables seamlessly.

💖 💪 🙅 🚩
enghaon
≀Paulo Portela

Posted on February 26, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related