Python OS Functions

Let’s talk about Python OS functions and how they can help you interact with the operating system (OS) in simple English. These functions allow you to perform tasks like creating files, deleting directories, changing permissions, renaming files, listing directory contents, traversing directories, getting file information, executing shell commands, and more!

Here are some of the most commonly used OS functions:
– os.mkdir(path): Creates a new directory at the specified path. If the directory already exists, an error is raised.
– os.rmdir(path): Deletes the empty directory with the given name or path. If the directory is not empty, an error is raised.
– os.chmod(filename, mode): Changes the permissions of a file or directory using octal notation (e.g., 0o755 for read/write access by owner and group, and read-only access for others).

Let’s say you want to create a new folder called “my_new_directory” in your current working directory. You can do this using the os module like so:

# Import the os module to access operating system functionalities
import os

# Use the mkdir function from the os module to create a new directory called "my_new_directory" in the current working directory
os.mkdir('my_new_directory')

# Print a message to confirm that the directory was created successfully
print("Directory created successfully.")

This code will first import the os module, then use its mkdir() function to create a new folder with the name “my_new_directory”. The print statement is used to display a message indicating that the directory was created successfully.

If you want to delete an empty directory called “my_empty_directory”, you can do this using the os module like so:

# Import the os module to access its functions
import os

# Use the mkdir() function to create a new folder named "my_new_directory"
os.mkdir('my_new_directory')

# Use the print statement to display a message indicating the directory was created successfully
print("New directory created successfully.")

# Use the rmdir() function to delete the empty directory named "my_empty_directory"
os.rmdir('my_empty_directory')

# Use the print statement to display a message indicating the directory was deleted successfully
print("Empty directory deleted successfully.")

This code will first import the os module, then use its rmdir() function to delete an empty folder with the name “my_empty_directory”. The print statement is used to display a message indicating that the directory was deleted successfully.

These functions can help you automate tasks that would otherwise be time-consuming or error-prone when done manually. With Python’s OS functions, you have the power to interact with your operating system in a simple and efficient way!

SICORPS