The os and shutil modules in Python are widely used for managing files and directories, as well as performing various file operations. Below are 10 Python code snippets demonstrating the capabilities of these modules.
1. Creating Directories with os.makedirs
import os# Create a directory along with intermediate directoriesdirectory_path ='parent_folder/child_folder'os.makedirs(directory_path,exist_ok=True)print(f"Directory created: {directory_path}")
os.makedirs creates directories, and the exist_ok=True argument ensures it doesn't raise an error if the directory already exists.
2. Renaming a File with os.rename
import os# Rename a fileold_name ='old_file.txt'new_name ='new_file.txt'os.rename(old_name, new_name)print(f"File renamed from {old_name} to {new_name}")
os.rename renames or moves a file. It works for both renaming and moving files across directories.
3. Removing a File with os.remove
os.remove deletes a file. You can use this method to delete files from the filesystem.
4. Listing Files in a Directory with os.listdir
os.listdir returns a list of files and directories in the specified path.
5. Copying a File with shutil.copy
shutil.copy copies the contents of a file to another location, preserving the file permissions.
6. Moving a File with shutil.move
shutil.move moves a file or directory to a new location, and it can also be used to rename files.
7. Removing an Empty Directory with os.rmdir
os.rmdir removes an empty directory. If the directory contains files, it will raise an error.
8. Deleting a Directory and Its Contents with shutil.rmtree
shutil.rmtree removes a directory along with all its contents, including files and subdirectories.
9. Getting File Information with os.stat
os.stat provides detailed information about a file, such as size, creation time, and last modification time.
10. Changing File Permissions with os.chmod
os.chmod changes the permissions of a file. In this case, it grants read and write permissions to the owner only.
These 10 snippets highlight the key functionalities of the os and shutil modules for handling file and directory operations in Python. These modules provide a wide range of useful tools for managing filesystem operations in a scriptable and automated manner.
import os
# Remove a file
file_path = 'file_to_delete.txt'
os.remove(file_path)
print(f"File {file_path} has been deleted")
import os
# List all files and directories in a specific path
path = '.'
files = os.listdir(path)
print(f"Files in {path}: {files}")
import shutil
# Copy a file from one location to another
src = 'source_file.txt'
dst = 'destination_file.txt'
shutil.copy(src, dst)
print(f"File copied from {src} to {dst}")
import shutil
# Move a file to a new location
src = 'source_file.txt'
dst = 'destination_folder/'
shutil.move(src, dst)
print(f"File moved from {src} to {dst}")
import os
# Remove an empty directory
dir_path = 'empty_folder'
os.rmdir(dir_path)
print(f"Empty directory {dir_path} has been removed")
import shutil
# Remove a directory and all its contents
dir_path = 'folder_to_remove'
shutil.rmtree(dir_path)
print(f"Directory {dir_path} and its contents have been deleted")
import os
# Get file status (e.g., size, timestamps)
file_path = 'some_file.txt'
file_stats = os.stat(file_path)
print(f"File size: {file_stats.st_size} bytes")
print(f"Last modified: {file_stats.st_mtime}")
import os
# Change file permissions to read and write for the owner
file_path = 'some_file.txt'
os.chmod(file_path, 0o600) # Read/write for owner only
print(f"Permissions for {file_path} have been changed")