CodeGym /Courses /Python SELF EN /Working with Directories

Working with Directories

Python SELF EN
Level 21 , Lesson 6
Available

7.1 Basic Operations

You've learned how to work with files, now let's work with directories. Sometimes it's similar to working with files, sometimes it's not. Directories have their own quirks. The main functions for working with directories are provided by the modules os and shutil.

Main operations with directories:

Creating a Directory

To create a new directory, use the function os.mkdir().

Example:


import os

# Creating a new directory
os.mkdir('new_directory')
print("Directory 'new_directory' created")

Creating Nested Directories

To create multiple nested directories, use the function os.makedirs().

Example:


import os

# Creating multiple nested directories
os.makedirs('parent_directory/child_directory')
print("Nested directories 'parent_directory/child_directory' created")

Removing a Directory

To remove an empty directory, use the function os.rmdir(). To remove a directory with contents, use the function shutil.rmtree().

Example:


import os

# Removing an empty directory
os.rmdir('new_directory')
print("Directory 'new_directory' removed")

Example of Removing a Directory with Contents:


import shutil

# Removing a directory with contents
shutil.rmtree('parent_directory')
print("Directory 'parent_directory' and all its contents removed")

Important! Never delete a directory with all its contents in one go. In one out of ten cases, a bug will sneak into your program, and you'll delete half of your files on the disk. Everyone goes through this. Just don't do it.

It's recommended to check for the existence of a directory before deleting it using the function os.path.exists(). This can prevent errors related to deleting a non-existent directory or wrong path.

Example:


import os
import shutil

# Checking if a directory exists before deleting
directory_path = 'parent_directory'
if os.path.exists(directory_path):
    shutil.rmtree(directory_path)
    print(f"Directory '{directory_path}' and all its contents removed")
else:
    print(f"Directory '{directory_path}' doesn't exist, can't delete")

7.2 Copying Directories

Moving and Renaming a Directory

To move or rename a directory, use the function os.rename().


import os

# Creating directory for example
os.mkdir('original_directory')

# Renaming directory
os.rename('original_directory', 'renamed_directory')
print("Directory 'original_directory' renamed to 'renamed_directory'") 

Copying a Directory

To copy a directory, use the function shutil.copytree(). This function not only copies the contents of the directory but also creates a new directory at the specified destination path.


import os
import shutil

# Creating directory for example
os.mkdir('source_directory')

# Copying directory
shutil.copytree('source_directory', 'destination_directory')
print("Directory 'source_directory' copied to 'destination_directory'")

7.3 Current Directory

Each running program is tied to a concept known as the "current working directory." Usually, this is the directory where the program is launched and where it looks for its service files. For example, all files whose paths are specified without a directory name will be searched in the current directory.

Getting the Current Working Directory

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


import os

# Getting the current working directory
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")

Changing the Current Working Directory

To change the current working directory, use the function os.chdir().


import os

# Changing the current working directory
os.chdir('new_directory')
print(f"Current working directory changed to: {os.getcwd()}")

Changing the current working directory can affect paths to files that are specified relative to the current directory. Be cautious when changing directories, as it can lead to errors if the program expects a file in the original directory.

Checking Directory Existence

To check if a directory exists, use the function os.path.exists().


import os

# Checking if a directory exists
directory_path = 'new_directory'
if os.path.exists(directory_path):
    print(f"Directory '{directory_path}' exists")
else:
    print(f"Directory '{directory_path}' does not exist")

Getting the Absolute Path of a Directory

To get the absolute path, use the function os.path.abspath().


import os

# Getting the absolute path of a directory
relative_path = 'example_directory'
absolute_path = os.path.abspath(relative_path)
print(f"Absolute path: {absolute_path}")

7.4 Directory Contents

Getting a List of Files and Directories

To get a list of files and directories in a specified directory, use the function os.listdir().


import os

# Getting a list of files and directories in the current directory
contents = os.listdir('.')
print(f"Contents of the current directory: {contents}")

You can work with files and directories not just as lists of paths, but as more complex objects.

Getting Information About Directory Contents Using os.scandir()

The function os.scandir() returns an iterator that yields DirEntry objects for each entry in the directory. These objects contain information about files and directories, which makes their use more efficient compared to os.listdir(), especially for large directories.


import os

# Getting information about directory contents
with os.scandir('.') as entries:
    for entry in entries:
        print(f"Name: {entry.name}, Is Directory: {entry.is_dir()}, Is File: {entry.is_file()}")
2
Task
Python SELF EN, level 21, lesson 6
Locked
Creating and Deleting Directories
Creating and Deleting Directories
2
Task
Python SELF EN, level 21, lesson 6
Locked
Getting a list of files and directories
Getting a list of files and directories
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION