Handling Directories and Files Using Python’s packages
Table of Contents
- Introduction to Python’s
os
andshutil
Packages - Creating Directories
- Listing Files in a Directory
- Moving and Copying Files
- Deleting Files and Directories
- Conclusion
Introduction to Python’s os
and shutil
Packages
Python provides built-in packages like os
and shutil
to handle directories and files efficiently. The os
package offers functions for interacting with the operating system, such as creating directories and navigating the file system. The shutil
package is useful for high-level operations on files and collections of files.
Creating Directories
Creating directories in Python is straightforward with the os.mkdir()
and os.makedirs()
functions.
- Using
os.mkdir()
import os
# Create a single directory
os.mkdir('new_folder')
Using os.makedirs()
import os
# Create a directory with nested folders
os.makedirs('parent_folder/child_folder')
Both functions will raise an error if the directory already exists, so you may want to check for its existence first:
import os
if not os.path.exists('new_folder'):
os.mkdir('new_folder')
Listing Files in a Directory
To list all files in a directory, you can use os.listdir()
:
import os
# List all files in the current directory
files = os.listdir('.')
for file in files:
print(file)
For more complex filtering, the glob
module is a powerful alternative:
import glob
# List all .txt files in the current directory
txt_files = glob.glob('*.txt')
print(txt_files)
Moving and Copying Files
The shutil
package offers simple functions to move and copy files.
Copying Files
import shutil
# Copy a file
shutil.copy('source.txt', 'destination.txt')
Moving Files
import shutil
# Move a file
shutil.move('source.txt', 'new_folder/destination.txt')
These functions are intuitive and make file manipulation straightforward.
Deleting Files and Directories
Deleting files and directories is risky, so always ensure you have backups before proceeding. The os.remove()
function is used for files, while os.rmdir()
and shutil.rmtree()
are used for directories.
- Deleting a File
import os
# Delete a single file
os.remove('file_to_delete.txt')
Deleting a Directory
import os
import shutil
# Remove an empty directory
os.rmdir('empty_folder')
# Remove a directory with its contents
shutil.rmtree('folder_to_delete')
Conclusion
Understanding how to handle directories and files is crucial for any Python developer. The os
and shutil
packages provide powerful tools to create, move, copy, and delete files and directories with ease. Whether you're automating tasks or building complex systems, these tools will be invaluable.