Nearby lessons

96 of 159

Python - Working with Directories

📌 What You Will Learn
  • Get the current working directory using os.getcwd()
  • Create a directory using os.mkdir() and nested directories using os.makedirs()
  • Remove empty directories using os.rmdir() and os.removedirs()
  • Rename a directory using os.rename()
  • List directory contents with os.listdir() and traverse them with os.walk()

Working with Directories

It is very common to perform operations on directories while working with files.

Python provides the built-in os module to perform directory-related operations.

The os module provides various functions to interact with the operating system, allowing us to create, remove, rename, and manage directories.

🐍Code Cell
1import os
Output
No output captured.

Q1. Know the Current Working Directory

The current working directory (CWD) is the directory from which the Python program is currently running.

To get the current working directory, use the os.getcwd() function.

🐍Code Cell
1import os
2 
3cwd = os.getcwd()
4 
5print("Current Working Directory:", cwd)
Output
No output captured.

Explanation

os.getcwd() returns the path of the current working directory.

Q2. Create a Subdirectory in the Current Working Directory

We can create a new directory inside the current working directory by using the os.mkdir() function.

🐍Code Cell
1import os
2 
3os.mkdir("mysub")
4 
5print("mysub directory created in cwd")
Output
No output captured.

Directory Structure

🐍Code Cell
1Current Working Directory
2
3└── mysub
Output
No output captured.

Q3. Create a Subdirectory Inside Another Directory

Suppose the following directory structure already exists:

🐍Code Cell
1Current Working Directory
2
3└── mysub
Output
No output captured.

Program

Create another directory named mysub2 inside mysub.

🐍Code Cell
1import os
2 
3os.mkdir("mysub/mysub2")
4 
5print("mysub2 created inside mysub")
Output
No output captured.

Directory Structure

🐍Code Cell
1Before
2 
3Current Working Directory
4
5└── mysub
6 
7 
8After
9 
10Current Working Directory
11
12└── mysub
13
14 └── mysub2
Output
No output captured.

Q4. Create Multiple Directories

If we want to create multiple directories in a single statement, Python provides the os.makedirs() function.

If the parent directories do not exist, Python automatically creates them.

🐍Code Cell
1import os
2 
3os.makedirs("sub1/sub2/sub3")
4 
5print("sub1 and in that sub2 and in that sub3 directories created")
Output
No output captured.

Directory Structure

🐍Code Cell
1Before
2 
3(Current directory is empty)
4 
5 
6After
7 
8sub1
9
10└── sub2
11
12 └── sub3
Output
No output captured.

Q5. Remove a Directory

To remove an existing empty directory, Python provides the os.rmdir() function.

The directory must be empty before it can be removed.

🐍Code Cell
1import os
2 
3os.rmdir("mysub/mysub2")
4 
5print("mysub2 directory deleted")
Output
No output captured.

Q6. Remove Multiple Directories

To remove multiple empty directories in a specified path, Python provides the os.removedirs() function.

🐍Code Cell
1import os
2 
3os.removedirs("sub1/sub2/sub3")
4 
5print("All 3 directories sub1, sub2 and sub3 removed")
Output
No output captured.

Q7. Rename a Directory

We can rename an existing directory by using the rename() function of the os module.

🐍Code Cell
1import os
2 
3os.rename("mysub", "newdir")
4 
5print("mysub directory renamed to newdir")
Output
No output captured.

Directory Structure

🐍Code Cell
1Before
2 
3Current Working Directory
4
5└── mysub
6 
7 
8After
9 
10Current Working Directory
11
12└── newdir
Output
No output captured.

Q8. Display the Contents of a Directory

The os module provides the listdir() function to display the contents of a specified directory.

Note: It displays only the contents of the specified directory. It does not display the contents of its subdirectories.

🐍Code Cell
1import os
2 
3print(os.listdir("."))
Output
No output captured.

Sample Output

Explanation

  • "." represents the current working directory.
  • The function returns a list containing all files and directories present in that directory.
  • It does not display the contents of subdirectories.

Q9. Display the Contents of a Directory Including Subdirectories

To display the contents of a directory along with all its subdirectories, Python provides the os.walk() function.

🐍Code Cell
1os.walk(path, topdown=True, onerror=None, followlinks=False)
Output
No output captured.

Explanation

The os.walk() function returns an iterator object whose contents can be displayed using a for loop.

For every directory visited, the loop receives:

  • dirpath - the current directory path.
  • dirnames - a list of all subdirectories inside the current directory.
  • filenames - a list of all files inside the current directory.

Program

🐍Code Cell
1import os
2 
3for dirpath, dirnames, filenames in os.walk("."):
4 
5 print("Current Directory Path:", dirpath)
6 print("Directories:", dirnames)
7 print("Files:", filenames)
8 
9 print()
Output
No output captured.

Sample Output

Difference Between listdir() and walk()

listdir() walk()
Displays the contents of the specified directory only. Displays the contents of the specified directory and all its subdirectories.
Returns a list. Returns an iterator.
Does not traverse the directory tree. Traverses the complete directory tree.

Summary of os Module Functions

Function Purpose
os.getcwd() Returns the current working directory.
os.mkdir() Creates a single directory.
os.makedirs() Creates multiple directories.
os.rmdir() Removes a single directory.
os.removedirs() Removes multiple directories.
os.rename() Renames a directory.
os.listdir() Lists directory contents.
os.walk() Traverses directories and subdirectories.
📝 Key Takeaways
  • The os module provides functions for all common directory operations
  • os.getcwd() returns the current working directory path
  • os.mkdir() creates one directory, while os.makedirs() creates multiple nested directories
  • os.rmdir() removes one empty directory and os.removedirs() removes a chain of empty directories
  • os.listdir() returns a list of the directory contents, while os.walk() traverses the full directory tree

🧠 Test Your Knowledge

8 Questions
Progress: 0 / 8