Python Directories

In Python, a directory, also known as a folder, is a way to organize and store files on a computer. The os module in Python provides several functions for interacting with the file system, including creating, removing, and manipulating directories. These functions allow for easy and efficient management of directories in a Python program.

Using these functions, one can easily manage directories in a Python program, for example, one can create, remove and list the directory, change the current working directory and many more. These functions are very useful when dealing with file management in python.

List of some common methods for working with directories in Python

1. os.mkdir(path): This method creates a new directory with the given path.

Example:

import os

os.mkdir("test")
print(os.listdir())
# Output: ['test']

2. os.makedirs(path): This method creates a new directory along with all its parent directories.

Example:

import os

os.makedirs("test1/test2")
print(os.listdir())
# Output: ['test1']
print(os.listdir("test1"))
# Output: ['test2']

3. os.rmdir(path): This method removes an empty directory with the given path.

Example:

import os

os.mkdir("test")
print(os.listdir())
# Output: ['test']
os.rmdir("test")
print(os.listdir())
# Output: []

4. os.removedirs(path): This method removes a directory and all its parent directories if they are empty.

Example:

import os

os.makedirs("test1/test2")
print(os.listdir())
# Output: ['test1']
os.removedirs("test1/test2")
print(os.listdir())
# Output: []

5. os.chdir(path): This method changes the current working directory to the given path.

Example:

import os

os.mkdir("test")
os.chdir("test")
print(os.getcwd())
# Output: /path/to/current/directory/test

6. os.getcwd(): This method returns the current working directory as a string.

Example:

import os

print(os.getcwd())
# Output: /path/to/current/directory

7. os.listdir(path): This method lists the files and directories in the given path. If the path is not provided, it will list the files and directories in the current working directory.

Example:

import os

os.mkdir("test")
print(os.listdir())
# Output: ['test']

8. os.path.exists(path): This method returns a Boolean indicating whether the provided path points to an existing file or directory.

Example:

import os

os.mkdir("test")
print(os.path.exists("test"))
# Output: True
print(os.path.exists("non_existent_dir"))
# Output: False

9. os.path.isdir(path): This method returns a Boolean indicating whether the provided path points to an existing directory.

Example:

import os

os.mkdir("test")
print(os.path.isdir("test"))
# Output: True
print(os.path.isdir("non_existent_dir"))
# Output: False

10. os.path.abspath(path): This method returns the absolute path of the provided path.
Example:

import os

print(os.path.abspath("test"))
# Output: /path/to/current/directory/test

11. os.path.basename(path): This method returns the base name of the provided path.

Example:

import os

print(os.path.basename("/path/to/file.txt"))
# Output: file.txt

12. os.path.dirname(path): This method returns the directory name of the provided path.

Example:

import os

print(os.path.dirname("/path/to/file.txt"))
# Output: /path/to

13. os.path.split(path): This method splits the provided path into a tuple containing the directory name and the base name.

Example:

import os

print(os.path.split("/path/to/file.txt"))
# Output: ('/path/to', 'file.txt')

14. os.path.splitext(path): This method splits the provided path into a tuple containing the file name and the file extension.

Example:

import os

print(os.path.splitext("/path/to/file.txt"))
# Output: ('/path/to/file', '.txt')

15. os.path.getsize(path): This method returns the size of the file in bytes for the provided path.

Example:

import os

with open("test.txt", "w") as f:
    f.write("test")
print(os.path.getsize("test.txt"))
# Output: 4

16. os.path.getmtime(path): This method returns the last modification time of the provided path as a timestamp.

Example:

import os
import time

with open("test.txt", "w") as f:
    f.write("test")
time.sleep(2)
with open("test.txt", "a") as f:
    f.write(" more test")
print(os.path.getmtime("test.txt"))
# Output: timestamp

17. os.path.normpath(path): This method returns a normalized pathname.

Example:

import os

print(os.path.normpath("/path/to/.././file.txt"))
# Output: /path/file.txt

How directories can be used in Python

1. Recursively traversing a directory structure:

import os

def traverse_directory(directory):
    for root, dirs, files in os.walk(directory):
        print(f"At directory {root}:")
        for d in dirs:
            print(f"    Found directory: {d}")
        for f in files:
            print(f"    Found file: {f}")

traverse_directory(".")

2. Creating a backup of a directory:

import os
import shutil

def create_backup(src, dest):
    shutil.copytree(src, dest)

create_backup("original_dir", "backup_dir")

3. Compressing a directory:

import os
import zipfile

def compress_directory(directory):
    with zipfile.ZipFile("archive.zip", "w") as archive:
        for root, dirs, files in os.walk(directory):
            for file in files:
                archive.write(os.path.join(root, file))

compress_directory("directory_to_compress")

4. Searching for a file in a directory:

import os

def search_file(directory, file_name):
    for root, dirs, files in os.walk(directory):
        if file_name in files:
            return os.path.join(root, file_name)
    return None

print(search_file(".", "file.txt"))

5. Renaming a directory:

import os

os.rename("old_dir_name", "new_dir_name")

6. Creating a directory with specific permissions:

import os

os.makedirs("test", mode=0o700)

7. Creating a temporary directory:

import tempfile

temp_dir = tempfile.TemporaryDirectory()
print(temp_dir.name)
# Output: /path/to/temp/directory

8. Listing all the subdirectories in a directory:

import os

sub_directories = [d for d in os.listdir() if os.path.isdir(d)]
print(sub_directories)

9. Counting the number of files in a directory:

import os

def count_files(directory):
    return len([f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))])

print(count_files("."))

Conclusion

In this article by TechVidvan, we can conclude by saying that directories, also known as folders, are an important aspect of file management in Python. The os module in Python provides a wide range of functions for interacting with the file system, including creating, removing, and manipulating directories. These functions allow for easy and efficient management of directories in a Python program. With the use of the os module and other libraries, directories can be used for a variety of tasks such as file management, backup, compression, traversing, and many more.

Python’s os module provides a simple and easy-to-use interface to interact with the file system and directories. It allows developers to perform various operations such as creating, renaming, deleting, and traversing directories. With the help of the os module and other libraries, Python can be used for a wide range of file management tasks, making it a powerful tool for managing and organizing files and directories.