9 Useful Tips Working with Operating System using Python

Being on Python, at times, you may feel the need to fetch your Operating System details for automating tasks or even for doing basic tasks. Here are helpful tips on how to retrieve the OS details, perform some basic tasks while using Python on your Linux system.

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

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

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()

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:-

Getting the size of terminal

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()

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

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.

listing files and folders in a 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

You may see the output of the above code as shown in the following image

listing files and directories

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

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"

    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:

creating a directory using python

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

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

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

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.

Roshan Agarwal
Roshan Agarwal is a python programmer and Linux lover; he is using and experimenting with python for a long time. He loves to write and review open-source software, command-line tools, and web applications. Apart from writing tutorials, he explores and contributes to open-source programs in GitHub.


Please enter your comment!
Please enter your name here





Buyers who wish to go for a machine that is based on Linux often show interest in Chromebooks due to the form factor and extended battery life capabilities. Although ChromeOS power these machines, users can still miss out on a more genuine Linux experience. For those who happen to agree, the new Lemur Pro by System76 might get some heads turning.
Linux is growing faster than ever. As per the latest report, there is a drop in the Windows 10 market share for the first time, and Linux's market share has improved to 2.87% this month. Most of the features in the list were rolled out in the Pop OS 20.04. Let's a detailed look into the new features, how to upgrade, and a ride through video.

5 ways to send emails using the command-line in Linux

Did you master using the command-line in Linux? There is no limit to what one can do via the Linux Terminal. One of such things we are going to discuss today are methods of sending an email using the command-line.

Linux Vs. Windows: 10 Key Differences to Know

Merely going by statistics, it is most likely that you are a Windows user.  After all, around  87.70% of all PCs around the world run on Windows with Linux, only accounting for 2.32%.

The 10 Best Linux Server Distros For Home And Businesses

By the year 2020, it is estimated that there are close to 600 Linux distributions in the market. It includes both servers and Desktop versions; therefore, if you are looking for lightweight Linux distribution for your old PC or a reliable desktop version for employees in your organization, you may be overwhelmed with the number of choices for finding one for your use.

6 Essential Command-Line Utilities Every Linux User Should Know

Last week, we shared with you several "cool and fun" commands to get comfortable and confident with the Linux command-line. In our quest to further aid Linux users with mastery of the command line, or CLI, we present you with a variety of command-line utilities essential for all Linux users, regardless of proficiency level.