Retrieving Operating System Information
To retrieve information about the current operating system, you can use theuname method from the OS module. This method returns an object containing details such as:
- The name of the operating system
- The machine name on the network
- The release and version of the operating system
- The hardware identifier
name property of this object returns:
"POSIX"for Linux-based systems,"NT"for Windows, and"Java"for platforms like Jython.
Creating Directories
Themkdir function allows you to create a new directory by specifying a path. The location of the newly created directory depends on how you specify the path:
- Using just the directory name (or with a leading
./) creates the directory in the current working directory. - Prefixing the directory name with
../creates it in the parent directory. - Specifying an absolute path (for example,
/python/new_directory) creates the directory in the designated folder at the root.
Listing and Creating Directories with Python
To create a new directory in the current working directory and then list its contents, you can use the following example:makedirs method is ideal. It allows you to create nested directories with a single call. For example, the following code snippet creates a directory with a subdirectory, changes into the newly created folder, and lists its contents:
getcwd method.
Deleting Directories
In addition to file operations, Python’s OS module allows you to delete files and directories. To delete an empty directory, use thermdir function. The example below demonstrates how to create an empty directory and then remove it:
The
rmdir function works only on directories that exist and are empty. Attempting to delete a directory that contains files or subdirectories will result in an error.removedirs function. For example:
Executing System Commands
The OS module also provides thesystem method, which allows you to execute shell commands directly from Python. For example, you can create a new directory using a system command as follows:
0 indicates success, while a non-zero value (commonly 1) indicates an error.
When executing system commands, always validate and sanitize any inputs to prevent security risks such as command injection.
Summary
In this lesson, you learned how to:- Retrieve operating system information using Python’s OS module.
- Create directories using both
mkdirandmakedirs. - List directory contents using
os.listdir(). - Delete directories using
rmdirandremovedirs. - Execute system commands with the
systemmethod.