88. Python's os and shutil Modules

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

Copy

import os

# Create a directory along with intermediate directories
directory_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

Copy

import os

# Rename a file
old_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

Copy

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

Copy

os.listdir returns a list of files and directories in the specified path.


5. Copying a File with shutil.copy

Copy

shutil.copy copies the contents of a file to another location, preserving the file permissions.


6. Moving a File with shutil.move

Copy

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

Copy

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

Copy

shutil.rmtree removes a directory along with all its contents, including files and subdirectories.


9. Getting File Information with os.stat

Copy

os.stat provides detailed information about a file, such as size, creation time, and last modification time.


10. Changing File Permissions with os.chmod

Copy

os.chmod changes the permissions of a file. In this case, it grants read and write permissions to the owner only.


Last updated