Working with folders in Python: a complete guide
Working with folders in Python is one of the fundamental skills for any developer. Python provides powerful built-in modules os and shutil, which allow you to perform all the basic operations with the file system: creating, copying, moving, renaming and deleting folders.
Getting and changing the working directory
Before you start working with folders, it is important to know which directory you are in and to be able to change the current working directory.
Getting the current working directory:
import os
current_directory = os.getcwd()
print(f"Current working directory: {current_directory}")
Changing the current working directory:
import os
new_directory = "/path/to/new/directory"
os.chdir(new_directory)
print(f"The current working directory has been changed to: {os.getcwd()}")
Creating new folders
Python offers two main ways to create folders: mkdir() to create a single folder and makedirs() to create a nested directory structure.
import os
# Create a new
os.mkdir folder ('new_folder')
# Creating a new and intermediate folder
os.makedirs('middle_folder/new_folder', exist_ok=True)
# exist_ok=True allows you not to cause an error if there is such a folder.
Important: The exist_ok=True parameter prevents the FileExistsError error from occurring if the folder already exists.
Checking the existence of a folder
Before creating or deleting a folder, it is recommended to check its existence.:
import os
folder_path = 'my folder'
if os.path.exists(folder_path):
print(f"Folder {folder_path} already exists")
else:
os.mkdir(folder_path)
print(f"Folder {folder_path} created")
Copying Folders
To copy folders with all the contents, use the copytree() function from the shutil module:
import shutil
# Copying a folder with all the contents
of shutil.copytree('original folder', 'new folder')
Note: The target folder must not exist in advance, otherwise an error will occur.
Moving and renaming folders
To move and rename folders, use the rename() functions from the os module and move() from the shutil module:
import os
import shutil
# Rename folder (in the same directory)
os.rename('old_name', 'new_name')
# Move a folder to another directory
shutil.move('source folder', 'destination folder/source folder')
# Move with renaming
shutil.move('source folder', 'destination folder/newname')
Deleting folders
Python provides several ways to delete folders, depending on whether the folder is empty or contains files:
import os
import shutil
# Deleting
an empty os.rmdir folder ('empty folder')
# Deleting a folder and all its contents
shutil.rmtree('folder with contents')
Caution: The rmtree() function permanently deletes the folder along with all its contents!
Getting a list of files and folders
To view the contents of the directory, use the following methods:
import os
# Getting a list of all items in
the items directory = os.listdir('.')
print("Contents of the current directory:", items)
# Getting folders only
folders = [item for item in os.listdir('.') if os.path.isdir(item)]
print("Folders only:", folders)
# Getting files only
files = [item for item in os.listdir('.') if os.path.isfile(item)]
print("Files only:", files)
Practical example: complex work with folders
Let's look at a complete example that demonstrates basic folder operations.:
import os
import shutil
# Creating a new directory
project_directory = "project_folder"
os.makedirs(project_directory, exist_ok=True)
# Creating subfolders
subdirectories = ["sources", "documents", "tests"]
for subdir in subdirectories:
os.makedirs(os.path.join(project_directory, subdir), exist_ok=True)
# Create a file in one of the subfolders
file_path = os.path.join(project_directory, "sources", "main.py ")
with open(file_path, 'w', encoding='utf-8') as f:
f.write("print('Hello, World!')")
# Copying the file
copied_file_path = os.path.join(project_directory, "sources", "main_copy.py ")
shutil.copy(file_path, copied_file_path)
# Creating an archive folder and moving the file
archive_dir = os.path.join(project_directory, "archive")
os.makedirs(archive_dir, exist_ok=True)
shutil.move(copied_file_path, os.path.join(archive_dir, "main_archived.py"))
# Output of the project structure
print(f"The project structure was created in: {project_directory}")
for root, dirs, files in os.walk(project_directory):
level = root.replace(project_directory, '').count(os.sep)
indent = ' ' * 2 * level
print(f"{indent}{os.path.basename(root)}/")
subindent = ' ' * 2 * (level + 1)
for file in files:
print(f"{subindent}{file}")
Error handling when working with folders
When working with the file system, you should always consider handling possible errors.:
import os
import shutil
try:
# Attempt to create a folder
os.mkdir('new_folder')
print("Folder created successfully")
except FileExistsError:
print("Folder already exists")
except PermissionError:
print("Insufficient permissions to create folder")
except OSError as e:
print(f"Operating system error: {e}")
try:
# Attempt to delete a folder
shutil.rmtree('folder to delete')
print('Folder deleted successfully')
except FileNotFoundError:
print("Folder not found")
except PermissionError:
print("Insufficient permissions to delete folder")
Conclusion
Working with folders in Python using the os and shutil modules provides all the necessary tools for effective file system management. Having mastered these basic operations, you will be able to create more complex programs for automating work with files and directories. Don't forget to always handle possible exceptions and check the existence of folders before performing operations.