Introduction
The os
module in Python provides a way to interact with the operating system, allowing you to perform various system-related tasks like file handling, directory operations, and environment variables management. This documentation will cover the main functionalities of the os
module with code examples and explanations.
Table of Contents
Getting Information About the OS
1.1. Getting the current working directory
1.2. Getting the list of files in a directory
1.3. Checking if a path is a file or directory
1.4. Getting file information (size, creation time, etc.)File and Directory Operations
2.1. Creating a new directory
2.2. Renaming a file or directory
2.3. Removing a file or directory
2.4. Changing the current working directoryPath Operations
3.1. Joining paths
3.2. Splitting paths
3.3. Checking if a path exists
3.4. Normalizing pathsEnvironment Variables
4.1. Getting the value of an environment variable
4.2. Setting an environment variable
1. Getting Information About the OS
1.1. Getting the current working directory
You can use the os.getcwd()
function to get the current working directory.
pythonimport os
current_dir = os.getcwd()
print("Current working directory:", current_dir)
1.2. Getting the list of files in a directory
The os.listdir()
function returns a list of files and directories in the specified path.
pythonimport os
path = "/path/to/directory"
files_list = os.listdir(path)
print("Files in the directory:", files_list)
1.3. Checking if a path is a file or directory
The os.path.isfile()
and os.path.isdir()
functions allow you to check if a path is a file or a directory, respectively.
pythonimport os
path = "/path/to/file_or_directory"
if os.path.isfile(path):
print("It is a file.")
elif os.path.isdir(path):
print("It is a directory.")
else:
print("Path does not exist.")
1.4. Getting file information (size, creation time, etc.)
You can use os.path
functions like os.path.getsize()
and os.path.getctime()
to get file information.
pythonimport os
file_path = "/path/to/file"
file_size = os.path.getsize(file_path)
file_creation_time = os.path.getctime(file_path)
print("File size:", file_size, "bytes")
print("File creation time:", file_creation_time)
2. File and Directory Operations
Code examples for creating, renaming, removing files/directories, and changing the current working directory can be added here.
3. Path Operations
Code examples for path manipulation and existence checks can be added here.
4. Environment Variables
Code examples for getting and setting environment variables can be added here.
Conclusion
The os
module in Python is a powerful tool for interacting with the operating system, allowing you to perform a wide range of tasks related to file and directory operations, path manipulation, and environment variables management. Using the functions provided by this module, you can efficiently handle various system-related tasks in your Python programs.
0 Comments