0% found this document useful (0 votes)
12 views

module 4 python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

module 4 python

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Module-4

What is the shutil Module?


The shutil module in Python is used for high-level file
operations like copying, moving, renaming, and deleting
files or folders.
Copying Files and Folders
1. Definition:
The shutil.copy() function copies a file to a destination.
2. The shutil.copytree() function copies an entire folder
and its contents to a new destination.
Example (Copying a File):
import shutil
from pathlib import Path

source = Path.home() / 'example.txt' # Source file


Path.home(): Gets the current user’s home directory (e.g., C:/Users/YourName on
Windows or /home/YourName on Linux).
destination = Path.home() / 'backup_folder' #
Destination folder
shutil.copy(source, destination)
Output:
Copies example.txt into the backup_folder with the same
name.

Example (Copying a Folder):


shutil.copytree(Path.home() / 'data_folder', Path.home() /
'data_backup')

Output:
Creates a new folder data_backup with all contents of
data_folder.
Moving and Renaming Files or Folders
Definition:
The shutil.move() function moves or renames files and
folders.
Example (Moving a File):
import shutil
from pathlib import Path

source = Path('C:/example.txt') # File to move


destination = Path('C:/new_folder') # Destination folder

shutil.move(source, destination)
Output:
Moves example.txt into the folder new_folder.
Example (Renaming a File):
import shutil
from pathlib import Path

source = Path('C:/example.txt') # File to rename


destination = Path('C:/new_folder/renamed_example.txt') #
New name and location

shutil.move(source, destination)

Output:
Moves example.txt into the folder new_folder and renames it
to renamed_example.txt.
Deleting Files and Folders
Definition:
•os.unlink(path) deletes a single file.
•os.rmdir(path) deletes an empty folder.
•shutil.rmtree(path) deletes a folder and all its contents.
Example:
import shutil
import os

# Deleting a file
os.unlink('C:/example.txt')

# Deleting an empty folder


os.rmdir('C:/empty_folder')

# Deleting a folder with all its contents


shutil.rmtree('C:/folder_to_delete')

Output:
The specified files and folders are permanently deleted.
Safe Deletion with send2trash
Definition:
The send2trash module moves files or folders to the
recycle bin instead of permanently deleting them.

Example:
from send2trash import send2trash
send2trash('C:/example.txt') # Moves the file to recycle bin

Output:
The file example.txt is sent to the recycle bin for safe
recovery later.
Walking a Directory Tree
Definition:
The os.walk() function allows you to traverse a directory
tree. It iterates through all folders, subfolders, and files
starting from a specified directory.
import os

for folder_name, subfolders, filenames in


os.walk('C:\\delicious'):
print(f"The current folder is {folder_name}")

for subfolder in subfolders:


print(f"SUBFOLDER OF {folder_name}: {subfolder}")

for filename in filenames:


print(f"FILE INSIDE {folder_name}: {filename}")

print('')
Explanation:
.os.walk() returns three values:
•folder_name: The name of the current folder being
processed.
•subfolders: A list of all subfolders in the current folder.
•filenames: A list of all files in the current folder.

.The program prints:


•The current folder name.
•All subfolders in the current folder.
•All files in the current folder.

.The for loops process and display the directory tree


structure.
Example Directory Structure:

C:\delicious
├── cats
│ ├── catnames.txt
│ └── zophie.jpg
├── walnut
│ ├── waffles
│ │ └── butter.txt
└── spam.txt
Output:
The current folder is C:\delicious
SUBFOLDER OF C:\delicious: cats
SUBFOLDER OF C:\delicious: walnut
FILE INSIDE C:\delicious: spam.txt

The current folder is C:\delicious\cats


FILE INSIDE C:\delicious\cats: catnames.txt
FILE INSIDE C:\delicious\cats: zophie.jpg

The current folder is C:\delicious\walnut


SUBFOLDER OF C:\delicious\walnut: waffles

The current folder is C:\delicious\walnut\waffles


FILE INSIDE C:\delicious\walnut\waffles: butter.txt
Compressing Files with the zipfile Module
Definition:
The zipfile module in Python allows you to create, read,
extract, and manage ZIP files. ZIP files are
compressed archives that can store multiple files and
folders efficiently.
1. Reading ZIP Files
You can read the contents of a ZIP file and get information about its files.
Example:
import zipfile
from pathlib import Path

# Path to the ZIP file


zip_path = r'D:\SIT_WORKSPACE\AIDS-1-SEM-2024\Main1.zip' # Use raw string

# Open the ZIP file


with zipfile.ZipFile(zip_path, 'r') as zip_file:
# List contents
print("Contents of ZIP file:", zip_file.namelist())
# Get info about a file (ensure the file exists in the ZIP)
try:
info = zip_file.getinfo('Main1/TXT1-A.txt') # Corrected file path
print("Original size:", info.file_size, "bytes")
print("Compressed size:", info.compress_size, "bytes")
except KeyError:
print("File 'Main1/TXT1-A.txt' not found in the ZIP archive.")
Extracting ZIP Files
You can extract all or specific files from a ZIP archive.
Example:
import zipfile
from pathlib import Path

# Path to the ZIP file


zip_path =
r'D:\SIT_WORKSPACE\AIDS-1-SEM-2024\Main1.zip'

# Extract files
with zipfile.ZipFile(zip_path, 'r') as zip_file:

zip_file.extractall(r'D:\SIT_WORKSPACE\AIDS-1-SEM-2024\M
ain_extracted_files')
Creating and Adding to ZIP Files
You can create a new ZIP file or add files to an existing one.

import zipfile
from pathlib import Path

# Create a new ZIP file


new_zip_path = Path(r'D:\SIT_WORKSPACE\AIDS-1-SEM-2024\new.zip')
file_to_add = Path(r'D:\SIT_WORKSPACE\AIDS-1-SEM-2024\TXT1-A.txt')

with zipfile.ZipFile(new_zip_path, 'w') as new_zip:


new_zip.write(file_to_add, arcname=file_to_add.name,
compress_type=zipfile.ZIP_DEFLATED)
print(f"File '{file_to_add.name}' added to '{new_zip_path.name}'")

You might also like