Directory in Python

FREE Online Courses: Click, Learn, Succeed, Start Now!

Directories are a great way of organizing our files in a Computer. In this article, we will learn about the basic meaning of a directory and a Current Working Directory. We will discuss all the Python functions that allow us to interact with the directories in one way or another.

What is a directory in Python?

Directories are generally known as Folders. They can either be empty or contain multiple files or sub-directories. They give us a simple yet elegant way of organizing our files. Python has a lot of functions that we can use to create, modify, or remove directories.

Current Working Directory (CWD) in Python

The current Working Directory is the directory from which we execute our Python file. For example, if the Python file that we are executing is in the directory ‘/Users/apple/Project’ then the CWD will also be ‘/Users/apple/Project’.

Python allows us to access and modify the CWD using a module called OS. It is a built-in module, so it comes ready to use with the Python Standard Library. We can import the module using an import statement.

getcwd() and chdir() are two functions in the OS module that we can use to access and modify the CWD.

Accessing the CWD in Python

We can use the getcwd() function from the OS module to access the CWD. It returns the Current Working Directory.

Example of using getcwd() in Python

import os

cwd = os.getcwd()
print(f"Current Working Directory: {cwd}")

Output

Current Working Directory: /Users/apple/PythonProjects/PythonGeeks

Changing the CWD in Python

We can change the Current Working Directory using the chdir() function. It is available in the OS module. It has no return value. We need to pass a

Example of using chdir() in Python

import os

print("Before changing:", os.getcwd())
os.chdir("/Users/apple/PythonProjects/PythonGeeks2")
print("After changing:", os.getcwd())

Output

Before changing: /Users/apple/PythonProjects/PythonGeeks
After changing: /Users/apple/PythonProjects/PythonGeeks2

Listing Files and Sub-directories in a Python Directory

listdir(path) returns a list of names of all files and directories present inside the passed directory. If no directory is passed, then it returns a list of files and directories inside the CWD. It is used to know what’s inside a directory. It is also available in the OS module.

Example of using listdir() in Python

import os
print("Files and directories inside the CWD:", os.listdir())

Output

Files and directories inside the CWD: [OS_demo.py’, main.py’, math_demo.py’, ‘imgs”]

Creating a New Directory in Python

mkdir(path[, mode]) function from the OS module creates the passed directory. It takes one argument, a string containing the directory that we want to create. It has no return value and raises a FileExistsError when the passed directory already exists.

Example of using mkdir() in Python

import os
print("Before creating:", os.listdir())
os.mkdir("Employees") # creates a directory called Employees
print("After creating:", os.listdir())

Output

Before creating: [‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
After creating: [‘Employees’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

Renaming a Python Directory

To rename a directory, we need to import the rename(old, new) function from the OS module. It. It has no return value.

Example of using rename() in Python

import os

print("Before renaming:", os.listdir())
print(os.rename("Employees", "Students"))
print("After renaming:", os.listdir())

Output

Before renaming: [‘Employees’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
None
After renaming: [‘Students’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

Verifying the Existence of a Directory

To check whether a directory exists or not, we need to import the exists(path) function from the os.path module. It returns True if the passed directory exists, otherwise, it returns False.

Example of using path.exists() in Python

import os

print(os.listdir())
print(os.path.exists(Students))
print(os.path.exists('Employees'))

Output

[‘Students’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
True
False

Removing a Directory in Python

rmdir(path) function from the OS module removes the passed directory. rmdir(path) only removes empty directories and it raises an OSError if the passed directory is not empty.

Example of using rmdir() in Python

import os
print("Before Removing:", os.listdir())
print(os.rmdir("Students"))
print("After Removing:", os.listdir())

Output

Before Removing: [‘Students’, ‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]
None
After Removing: [‘OS_demo.py’, ‘main.py’, ‘math_demo.py’, ‘imgs’]

Last Modification Time of a Python Directory

In Python, we can access the last modification time of a directory by using the function getmtime(path) which is available in the os.path module. It takes a path-like object of the directory as an argument and returns a floating-point value which can be converted to a date-time object using the datetime module.

Example of using path.getmtime() in Python

import os
import datetime

m_time = os.path.getmtime('/Users/apple/PythonProjects')
print(m_time)
time = datetime.datetime.fromtimestamp(m_time).strftime("%d-%m-%Y %H:%M:%S")
print(f"The Directory is last modified on {time}")

Output

1625205596.6432579
The Directory is last modified on 02-07-2021 11:29:56

Last Access Time of Python Directory

We can access the last access time of a directory by using the getatime(path) function. The function is available in the module os.path and takes a path-like object of the directory as an argument. It returns a floating-point value that can be converted to a readable date by using the datetime module.

Example of using path.getatime() in Python

import os
import datetime

a_time = os.path.getatime('/Users/apple/PythonProjects')
print(a_time)
time = datetime.datetime.fromtimestamp(a_time).strftime("%d-%m-%Y %H:%M:%S")
print(f"The Directory is last accessed on {time}")

Output

1625206269.459917
The Directory is last accessed on 02-07-2021 11:41:09

Creating Platform-independent Directories in Python

To create a platform-independent directory, we must not use forward slashes or backward slashes. Python gives us two functions split() and join() to remove and add appropriate slashes depending on the platform. These two functions are available in the os.path module.

split(path)

The function removes the separators and splits the passed path into multiple components. It returns a tuple containing the components of the directory.

Example of using split() in Python

import os.path

dir = "/Users/apple/PythonProjects/PythonGeeks"
print(os.path.split(dir))

Output

(‘/Users/apple/PythonProjects’, ‘PythonGeeks’)

join(path, *paths)

The function joins the passed components and returns a directory with appropriate separators.

Example of using join() in Python

import os.path

dir = ('/Users/apple/PythonProjects', 'PythonGeeks')
print(os.path.join(dir[0], dir[1]))

Output

/Users/apple/PythonProjects/PythonGeeks

Traversing Directories Recursively using Python

walk() is a generator from the OS module. It traverses through the passed directory. It yields a tuple containing the string of the directory, a list of directories, and a list of files for every directory it traverses.

Example of using walk() in Python

import os

for i, j, k in os.walk(os.getcwd()):
   print("path:", i)
   print("List of directories:", j)
   print("List of files:", k)

Output

path: /Users/apple/PythonProjects/PythonGeeks
List of directories: [imgs]
List of files: [‘OS_demo.py’, ‘main.py’]
path: /Users/apple/PythonProjects/PythonGeeks/imgs
List of directories: []
List of files: [‘img1.png’]

Getting the Size of a Directory in Python

To get the size of a directory, we need to import the get_size(path) function from the os.path module. It returns the size of the passed directory in bytes.

Example of using path.get_size() in Python

import os
print(os.path.getsize('PythonGeeks'))

Output

1852

Comparing Directories with Python

We use the module filecmp to compare directories in Python. It has several useful functions and classes to compare directories using Python.

cmpfiles(dir1, dir2, common)

The function cmpfiles() which is available in the filecmp module is used to check whether multiple files in two directories are equal or not.

The paths of two directories and a list containing the names of the files that need to be checked should be passed to the function.

It returns a tuple containing three lists. A list of matched files, a list of mismatched files, and a list of error files.

Example of using cmpfiles() in Python

import filecmp as fc

dir1 = "/Users/apple/PythonProjects/PythonGeeks"

common = ["geeks.py"]
print(fc.cmpfiles(dir1, dir1, common))

Output

([‘geeks.py’], [], [])

dircmp

To get a detailed comparison of any two directories, we first need to create an object of the class dircmp. The class compares the two passed directories.

Example of using dircmp in Python

import filecmp as fc

dir1 = "/Users/apple/PythonProjects/Calculator"
dir2 = "/Users/apple/PythonProjects/PythonGeeks"

cmp = fc.dircmp(dir1, dir2)
print(cmp)

Output

<filecmp.dircmp object at 0x10aff4310>

We can view the comparison results by using any of the three following methods.

report()

The method report() returns a detailed report on the comparison between the passed directories.

Example of using report() in Python

print(cmp.report())

Output

diff /Users/apple/PythonProjects/Calculator /Users/apple/PythonProjects/PythonGeeks
Only in /Users/apple/PythonProjects/Calculator : [‘calculator.py’]
Only in /Users/apple/PythonProjects/PythonGeeks : [‘geeks.py’]
None

report_partial_closure()

The method returns a report on the comparison between the passed directories including the sub-directories.

Example of using report_partial_closure() in Python

print(cmp.report_partial_closure())

Output

diff /Users/apple/PythonProjects/Calculator /Users/apple/PythonProjects/PythonGeeks
Only in /Users/apple/PythonProjects/Calculator : [‘calculator.py’]
Only in /Users/apple/PythonProjects/PythonGeeks : [‘geeks.py’]
None

report_full_clousre()

The method returns a report on the comparison between the passed directories including the sub-directories recursively. It is similar to the method report_partial_closure. The report_partial_closure is non-recursive whereas the report_full_closure is recursive.

Example of using report_full_closure() in Python

print(cmp.report_full_closure())

Output

diff /Users/apple/PythonProjects/Calculator /Users/apple/PythonProjects/PythonGeeks
Only in /Users/apple/PythonProjects/Calculator : [‘calculator.py’]
Only in /Users/apple/PythonProjects/PythonGeeks : [‘geeks.py’]
None

Interview Questions on Python DIrectory

Q1. Write a program to get and change the Current Working Directory to ‘/Users/apple/PythonProjects/Calculator’.

Answer 1. Complete code is as follows:

import os
print(os.getcwd())
os.chdir('/Users/apple/PythonProjects/Calculator')
print(os.getcwd())

Output

/Users/apple/PythonProjects/PythonGeeks
/Users/apple/PythonProjects/Calculator

Q2. Write a program to list all files and directories present inside the directory “/Users/apple/PythonProjects”.

Answer 2. Complete code is as follows:

import os
print(os.listdir("/Users/apple/PythonProjects"))

Output

[‘PythonGeeks’]

Q3. Write a program to create a new directory “/Users/apple/PythonProjects/PythonGeeks2”.

Answer 3. Complete code is as follows:

import os

os.mkdir("/Users/apple/PythonProjects/PythonGeeks2")
print("Directory Created")

Output

Directory Created

Q4. Write a program to delete a directory “/Users/apple/PythonProjects/PythonGeeks2” if it exists, otherwise, create that directory.

Answer 4. Complete code is as follows:

import os

dir = "/Users/apple/PythonProjects/PythonGeeks2"
if os.path.exists(dir):
   os.rmdir(dir)
   print("Directory Removed")
else:
   os.mkdir(dir)
   print("Directory Created")

Output

Directory Removed

Q5. Write a program to get the size of the CWD.

Answer 5. Complete code is as follows:

import os

print(os.path.getsize(os.getcwd()))

Output

640

Quiz on Python DIrectory

Conclusion

In this article, we have learned about the directories and how to use Python to access or modify those directories. We also learned about the Current Working Directory and the functions that are available in Python to access and modify the Current Working Directory.

In addition, if you have any comments, please feel free to leave them in the comments section.

Did you like this article? If Yes, please give PythonGeeks 5 Stars on Google | Facebook


Leave a Reply

Your email address will not be published. Required fields are marked *