LAB-7
Develop a program to backing Up a given Folder (Folder in a current working
directory) into a ZIP File by using relevant modules and suitable methods.
import os
import zipfile
def backup_folder(folder_name):
folder_path = os.path.abspath(folder_name)
backup_file = folder_name + '.zip'
with zipfile.ZipFile(backup_file, 'w') as zf:
for root, dirs, files in os.walk(folder_path):
for file in files:
file_path = os.path.join(root, file)
zf.write(file_path, os.path.relpath(file_path, folder_path)) # Ensure file path is
relative
# Call the function to back up folders
backup_folder('example_folder')
backup_folder('xyz_folder')
Algorithm:
1. Start
2. Define the function backup_folder(folder_name):
• Input: folder_name (the name of the folder to back up).
3. Get the absolute path of the folder:
• Use os.path.abspath() to get the absolute path of folder_name.
4. Define the backup file:
• Create a backup_file name by appending .zip to folder_name.
5. Open a Zip file for writing:
• Use zipfile.ZipFile(backup_file, 'w') to open the zip file for writing.
6. Traverse the folder:
• Use os.walk(folder_path) to walk through the folder and its subfolders.
• For each subdirectory and file:
• Get the full file path using os.path.join(root, file).
7. Write each file to the zip file:
• Use zf.write(file_path, os.path.relpath(file_path,
folder_path)) to add the file to the zip archive.
• This ensures that the file path inside the zip file is relative to the original folder path,
preserving the folder structure.
8. Close the zip file:
• The zip file is automatically closed after exiting the with block.
9. Call the function to back up folders:
• Call backup_folder('example_folder') to back up the
example_folder.
• Call backup_folder('xyz_folder') to back up the xyz_folder.
10.End
Output:
Example_folder and xyz_folder are created in the same location