
Posted on • Edited on
Exploring the os Library With Python
Introduction
Theos
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 theos
module and demonstrates its utility through practical examples.
Topics
- File and directory operations
- Process management
- Environment variables manipulation
File and Directory Operations
Theos
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
importos# Check if a file existsfile_path="example.txt"ifos.path.exists(file_path):print("File exists.")else:print("File does not exist.")
Output:
File does not exist.
Creates a new folder
importos# Create a directorydirectory_path="example_directory"os.mkdir(path=directory_path)print("Directory created.")
Output:
Directory created.
Renames a file
importos# Rename a filefile_path="example.txt"new_file_path="new_example.txt"os.rename(file_path,new_file_path)print("File renamed.")
Output:
File renamed.
Lists the files found within a directory
importos# List files in a directorydirectory_path="example_directory"files=os.listdir(path=directory_path)print("Files in directory:",files)
Output:
Files in directory: ['example.txt']
Deletes a directory as long as it is empty
importos# Remove a directorydirectory_path="example_directory"os.rmdir(path=directory_path)print("Directory removed.")
Output:
Directory removed.
Process Management
With theos
module, you can interact with processes, including launching new processes, obtaining process IDs, and managing process attributes.
importos# Launch a new processos.system("ls -l")# Get the process ID of the current processpid=os.getpid()print("Process ID:",pid)# Get the parent process IDppid=os.getppid()print("Parent Process ID:",ppid)
Output:
total 96-rw-r--r--@ 1 tlayach staff 0 Feb 26 00:03 example.txt
Environment Variables Manipulation
Theos
module enables manipulation of environment variables, allowing you to retrieve, set, and unset environment variables.
importos# Get value of an environment variablepython_path=os.getenv("PYTHONPATH")print("PYTHONPATH:",python_path)# Set an environment variableos.environ["NEW_VARIABLE"]="new_value"print("NEW_VARIABLE set.")# Unset an environment variableos.environ.pop("NEW_VARIABLE",None)print("NEW_VARIABLE unset.")
Output:
PYTHONPATH: /Users/...NEW_VARIABLE set.NEW_VARIABLE unset.
Conclusion
Theos
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.
Top comments(1)
For further actions, you may consider blocking this person and/orreporting abuse