Python OS module
The OS module in Python provides an easy way to access operations related to the operating system.
Using the functions provided in this module you can access information about the OS and also access plenty of functionalities of your operating system.
name() function returns the name of the operating system module that has been imported by the user.
The ‘nt‘ is an implementation module used by the OS module. Therefore, when we used the name() function, it returns ‘nt‘.
Other names that have been currently registered are ‘posix‘ and ‘java‘.
getcwd() and chdir()
The getcwd() function returns the current working directory.
You can, however, change the current working directory easily. This can be done using chdir() method. Let’s check the below example.
The new working directory, as you can see, is different from the old one.
mkdir() and makedirs()
mkdir() method is used to create new directories in Python. You can specify the access mode of the directory.
The access mode decides whether different users can access, write or read the newly created directory.
Let’s create a new directory using mkdir() function.
The function took the path of the directory to be created as an argument. If you navigate to that path, you can access the newly created directory.
makedirs(name, mode, exist_ok)
The OS module makes you able to create multiple directories at once using the makedirs() method.
Basically, makedirs() function creates all the non-existent directories specified in the path. The exist_ok is by default set to False, it means that the method will raise an FileExistsError if one of the directories in the path already exists.
Remove Files and Directories
The remove() function in the os module is used to remove or delete a file specified in the path.
Let’s remove a text file that is located at “C:\Users\username\example.txt“. This can be done easily like as shown in the example below.
As mentioned in the section above, rmdir() method is used to remove an empty directory. So after creating a directory at the same path as in the example above, we can proceed to remove the directory.
listdir() method returns the names of all the files and directories at the specified path.
This is a really nice way to check files at a path when you do not use the graphical interface.
As the name suggests, you can rename files using rename() method. The file can only be renamed if the user has privileges to access and rename the files.
Python will move the file after renaming it to the current working directory.