The os module has a lot of uses that you can encounter in many parts of a series of articles. Still, we will try to cover many of the most used ones to teach python language users how they can interact with their operating system and files using python.
1. Remove a Directory
Removing a directory is easy as removing the files, as you saw in the previous tutorial. The problem is that the os module in python only removes the empty Directory, not a directory with files. Let’s see an example:
import os
# Directory Path
Path = "/home/abdelhakim/Thanks/"
# Remove Directory
os.rmdir(Path)
We’ve added the path of the “Thanks” directory to a variable, and then we use the .rmdir() function (Remove Directory) to remove that Directory. Try to execute this command on a folder (Directory) with even one file, and you will get an OSError error. Let’s fix this:
import os
# Directory Path
Path = "/home/abdelhakim/Thanks/"
try:
# Remove Directory
os.rmdir(Path)
except:
# Print a Message
print("The folder is not empty")
The code above will print a message since the “Thanks” folder is not empty, and if you want to remove the directories with files, you can use the shutil module.
2. Calculating The File Size
Using a straightforward command, you can use the os module to calculate the file size in bytes. Remember that this command will raise an OSError if the path does not exist so that you may use try/except in your code. Let’s see an example:
import os
# File Path
Path = "/home/abdelhakim/Thanks/Example.txt"
# Calculate The File Size
size = os.path.getsize(Path)
# Print The File Size
print("The file size is", size, "bytes")
You can see the os.path.getsize() function will give you the file size in bytes after you specify it. We all know there are 1 million bytes in 1 MB so if you have a vast number in the result, divide it by 1 million to get the accurate size in MB.
3. Check The File Path
Before you try to apply any function on the remove it, for example, rename it, add data, or any operations, you need to verify the file path. Because you can’t apply any function to a file that does not exist. Let’s see how you can verify the file path:
import os
# File Path
Path = "/home/abdelhakim/Thanks/Example.txt"
# Verify The File existence
print(os.path.exists(Path))
When you run the code, the os.path.exists() function will try to verify the file existence and return True if the file is there. Otherwise, you will get the False value.
4. Operating System Information
You’ve installed a new Linux distribution from hundreds of Linux distributions, and you want to get some information about the system using python. This os module can help you to have some basic information about your system using one command:
import os
# Get The System Information
print(os.uname())
You will have a lot of information when you run the os.uname() function, such as the operating system, the version of your system, the node name, and more information.
5. User’s Environmental Variables
Most computer users don’t know that some environmental variables are set on their computers. These variables can give you much helpful information about your computers, such as computer name, the type of your central processing unit (CPU), and more. Let’s see how you can get these environmental variables:
import os
# Get The Environmental Variables
print(os.environ)
We’ve used the .environ function, and it will print a lot of information on the screen about your system. When you run the code on another computer, you will get another piece of information since there are different users and operating systems.
6. Rename a File
The os module is developed to work with operating systems and also files. One of the operations you can make on files is renaming them. Let’s see a simple example to rename a file:
import os
# File Path
Path = "/home/abdelhakim/Thanks/Example.txt"
# Rename The File
os.rename(Path, "File.txt")
The file name was “Example.txt” but we’ve changed its name to “File.txt” using the .rename() function. This function is easy to use, and it will give you an error if the file doesn’t exist, so you may need to use try/except in your program to prevent stopping your program if the file is not there.
7. Open Different Files Types
The computer can read many file types such as mp3, pdf, words documents, txt, mp4, etc. But for every file type, an associated program should be installed in your system. If you want to open every file with its associated program using python, then you need to use this os function:
import os
# File Path
Path = "/home/abdelhakim/Thanks/Example.txt"
# Open The File
os.startfile(Path)
You can see we’ve used the .startfile() function to open the pdf file, and you only need to specify the file path, and that’s all. Unfortunately, this .startfile() function is available only in Windows operating system
8. Show Sub-Directories
Before, we’ve learned how to work with directories (Folders), meaning removing a directory, making a new one, and more. But did you know that you can see all of the sub-directories of a particular folder? Let’s see a simple example:
import os
# Directory Path
Path = "/home/abdelhakim/Thanks/"
# Print The Directory Files & Sub-Directories
for dirpath, dirnames, filenames in os.walk(Path):
print(dirpath)
We’ve used the .walk() function and loop over its values: the dirpath, dirnames, filenames, and we print only the dirpath to see the subdirectories of this folder.
Conclusion
Thanks for reading! At this point in the second part of the os module, you should now be familiar with it. You have at least a basic understanding of how you can interact with the operating system and files using the python programming language.