The OS Module In Python- Part 1

Python is more than just a fabulous language to learn. It is straightforward and provides simple commands & syntax to understand, work with, and remember. One of the good and worthy learning modules is the os module which allows you to interact with different operating systems such as Windows and Linux.

1. Getting The Local Directory

The local directory in python means the python file location you are working on your operating system. It always referred to CWD, which stands for Current Working Directory, and there is a simple function to get that path. Let’s see how we can do this:

import os

# Get The Local Directory
local = os.getcwd()

# Print The Local Directory
print(local)

First, we import the os module, which is installed by default in your python interpreter. Then, we use the .getcwd() function to get the current working directory and print it later on the screen. Try to change the location of the python file you are working on it, and the result will be different.

2. Changing The Local Directory

Sometimes you want to change the location you are working on instead of taking your python file to that location which doesn’t make sense, but it will work. It looks not professional to do the previous method so let’s find out how you can change the location:

import os

# Change The Directory
new = os.chdir("/home/abdelhakim/Documents/")

# Print The Local Directory
print(os.getcwd())

We’ve used the .chdir() function to change the directory, and you need to pass the new directory as a string. Later, we print the local directory, and you can see it changed if you compare it to the previous code. 

If the directory is not there, the program will be interested and raise a FileNotFoundError error. To fix this, we will use the try/except statements:

import os

try:    
    # Change The Directory
    new = os.chdir("/home/abdelhakim/Document/")
    
    # Print The Local Directory
    print(os.getcwd())

except FileNotFoundError:    
    # Print a Message
    print("File not found")

First, it will try to change the directory, and if it is found, it will print the new local directory. But if the directory is not there, it will print the message inside the except statement. I’ve misspelled the Documents directory by removing the “s” at the end to raise an error and get the message.

3. Create a Directory

If you need to create a directory in your system, we all know how you can perform this using the graphical interface of your system, but what about using python to do this? Let’s find out how the built-in os module can help:

import os

# Create a Directory
os.mkdir("Thanks")

We use only one simple command to create a directory in python, which is the .mkdit() function. You need to specify the directory name you want to create. That’s all. If you create a directory without specifying a path, it will be created in the local directory you are working on. 

What if you are working on this local directory, but you want to create a directory in another path? Let’s find out how you can perform this:

import os

# Directory You Want To Create
Directory = "Thanks"

# The Path 
Path = "/home/abdelhakim/"

# The Full Path
New_File = os.path.join(Path, Directory)

# Create a Directory
os.mkdir(New_File)

We’ve specified the directory you want to create, “Thanks” and the new path you want the directory to be in, which is “/home/abdelhakim/” and we can join them using the os.path.join() function and pass the result to the .mkdir() function.

4. Create Many Sub-Directories

Sometimes you need not just create a directory but also another directory inside this newly created one. For this purpose, we have another function to perform this action. Let’s see an example:

import os

# Directory You Want To Create
Directory = "Thanks/Welcome"

# The Path 
Path = "/home/abdelhakim/"

# The Full Path
New_File = os.path.join(Path, Directory)

# Create a Directory
os.makedirs(New_File)

The code here is the same as the previous one except for two changes. You could notice the first change is making another directory (sub-directory) called “Welcome” inside the directory “Thanks” and we’ve changed the function .mkdir() to the .makedirs() function.

5. List All Files & Directories Inside A Directory

You can know all the files and directories of your local path using only one simple function. Let’s see an example:

import os

# List All Files & Directories
print(os.listdir())

The .listdir() function will list all files & directories inside the local path. But what if you want to see the files and directories in another path? Let’s see also an example:

import os

# New Path
Path = "/home/abdelhakim/Thanks/"

# List All Files & Directories
print(os.listdir(Path))

This new code is straightforward to understand. Just specify the new directory you want to see its files inside and pass that variable to the .listdir() function, and it will work correctly.

6. Deleting a File

Deleting a file is also made accessible when you are using python language with the power of the os module since it is created to do everything you can do with the graphical interface of your system. Let’s see an example:

import os

# New Path
Path = "/home/abdelhakim/Thanks/Example.txt"

# Remove The File
os.remove(Path)

First, I’ve specified the file path I wanted to remove with its name, the “Example.txt” file, and we used the .remove() function from the os module and specified the full file path.

Conclusion

Thanks for reading! The os module in python is very extensive, and you can cover all of its functions in just one part. You will need to use this os module in many of your programs if you interact with the local system, so it is worth learning this module if you are new to the language, and it will show you the power of python.

Scroll to Top