There are several situations when we want to work with the operating system using Python. We may want to see the user details or wish to do some tasks with the files and directories. If you are a system administrator, you will find it useful to work with Operating System as one can easily automate some repeating tasks of the Operating System using Python.
Although the same tasks can be performed using basic shell scripting, it has limited capabilities and will not give you so much power as in Python. Additionally, the same python script can be used anywhere and also integrate the codes to other python projects. There are a vast number of modules to work with the Operating System in Python. Some of the modules which are included in Python’s standard library and work well with Operating Systems are os/path, pwd, glob, shutil, and subprocess.
Before getting started with this tutorial, you need to have Python installed. If you don’t have it installed already, refer our step by step guide to install Python on Linux.
Fetching OS Information using Python
At times you may want to fetch necessary information of the operating system like the username, user id, or merely the name of the operating system. Besides, the program may need to know which Operating System is running on so that it can tweak the tasks for different OSes.
1. Getting the operating system details
We can get operating system details like platform, name of Linux distribution (if using Linux), system OS name, etc. using Python. To get the name of the Operating System, we can use the modules os or sys. These modules are included in Python’s standard library, so we don’t need to install them for use in our projects. You can open the python shell by typing Python or python3 in the system terminal.
You can get the type of OS using the os library by running the following code in the python shell.
>>> import os
>>> os.name 'posix'
As you can see, the above code had display posix for Linux Operating System. If you are using Windows, it will show ‘nt.’ You can also get the Operating System name by using the sys module. You can run the following code to see how it works.
>>> import sys
>>> sys.platform 'linux'
As you can see, the result of the platform function of the sys module has shown the name Linux as I am using it. You will get “win 32” for windows.
You can use the uname function of the os module to get a detailed description, see the following code to see how it works.
>>> import os >>> os.uname() posix.uname_result(sysname='Linux', nodename='kali', release='5.6.0-kali2-amd64', version='#1 SMP Debian 5.6.14-2kali1 (2020-06-10)', machine='x86_64')
This code has shown that I am using the Kali Linux. This code is only available for Linux OS. It does not apply to Windows.
2. Getting the username using Python
You can get the name of the current user login in the system using Python by typing the following code in the python shell :
>>> import os >>> os.getlogin() 'roshan'
3. Getting the size of the terminal
You can also get the size of the terminal using Python. Run the following code in the python shell.
>>> import os >>> os.get_terminal_size() os.terminal_size(columns=80, lines=23)
This will print the size of the current terminal. This will write two values the number of columns and the number of lines. Individual columns or lines can be accessed using the following code. Copy the following program in a file name it terminal.py and run it using python3 terminal.py.
import os col, lines = os.get_terminal_size() print("Number of columns :",col) print("Number of lines :",lines)
You may see the output of the program as shown below:-
Performing basic operations with Files and Directories
Let’s now check out how to work with the files and directories using Python. Python has become a mature programming language, and it can now do tasks for which we need to learn different programming languages. Python is also good at automating several task-related to files and folders, and by using the following codes in an automated manner. You can perform automation like folder cleaning, moving files with specific formats from one place to another, etc.
4. Getting the Current Directory path
To get the current directory path, we can use the getcwd() function of the os module; it is much like the pwd command of Linux shell.
>>> import os >>> os.getcwd() '/home/roshan/Documents/fosslinux'
As you can see, the code had output the path of the directory in which I am using the python shell.
5. List all files and folders present in a directory
You can also list all the files and subdirectories present in a directory. To list the files and folders in the current directory, run the following code:
>>>import os >>>os.listdir()
The output resembles something like the below image. The above code is displaying a python list of all the files and directories present in the current working directory.
You can also list the files and sub-directory present in another directory by giving the path of the directory in the parenthesis. See the following code to understand how it works.
>>>import os >>>os.listdir("
You may see the output of the above code as shown in the following image
The output given by the listdir(
"D:/python") method is a python list of all the files and directories present in the directory
"D:/python". If the directory path which you provide in the parenthesis does not exist in the system, then it will raise a FileNotFoundError.
6. Creating a Directory
To create a directory using Python, you need to use the mkdir function of Python’s os module. Let’s see how to create a directory using Python. Run the following code in the python shell.
>>>import os >>>os.mkdir("os")
This will create a directory os in the current directory. If the directory already exists then you will get a FileExistError; It may look something like this:
Traceback (most recent call last): File "<stdin>", line 1, in <module> FileExistsError: [Errno 17] File exists: 'os'
For better error handling using try and except. You need to simply copy the code and paste it into a file named makedir.py and run the python program using the command
python3 makedir.py in your terminal ;
import os path = "os" try: os.mkdir(path) print("The Directory has been created successfully") except FileExistsError: print("The Directory named " + path + " already exists")
You may see the output something like in the following image:
The difference in the first code and the above code is that the second program uses a try/except method for error handling. The role of the try/except method in the above code is that the python interpreter will try to run the code under the try block first and if it got a FileExistError, than it will execute the code under the except block. This is a good practice to use try/except block in a python program so you can easily detect error and can run the code block present in the except part if there is an error.
7. Rename a File
You can also rename a file using Python. To rename a file, use the rename function of the os module. The rename function accepts two important arguments, the first argument is the path to the file you want to rename, and the other file is the name to which you want to rename the original file. See the code presented below to see how it works, type the code in the python shell, and see its working.
>>>import os >>>os.rename("file1.txt,file2.txt")
The above code will rename the file file1.txt with the name file2.txt. This will show an error if the file file1.txt is not present in the given path, so provide the correct path.
8. Delete a file
To delete a file, you need to use the remove() function of the os module. Look at the following code to see how to do this –
>>>import os >>>os.remove("sample.txt")
This will delete the file sample.txt present in the current directory; you can also give the path of the file if it is present in other directories. If the file does not exist in the given path, you will get a FileNotFoundError. Use the exception handling method outlined in the previous sub-topic to deal with errors.
9. Delete a directory
If the provided path is a directory, you will get OSError because this function can’t be used to remove a directory. Use
rmdir()method to remove the directories. See the following code for better illustration-
>>>import os >>>os.rmdir("sample_dir")
The above code will remove the directory named sample_dir. Give the path of the folders if present in other directories to remove them.
That’s all about various useful tips for effectively fetching the operating system and other info that you need while using Python. What other tips you have that you are willing to share? Do let us know in the comments below. Before leaving, you may also like to see the tutorial on how to execute shell command with Python, which shows you how to use the Linux shell commands easily under python programs.