module 4 python
module 4 python
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
shutil.move(source, destination)
Output:
Moves example.txt into the folder new_folder.
Example (Renaming a File):
import shutil
from pathlib import Path
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')
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
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.
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
# 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