7pgm Python
7pgm Python
1. Imports:
import zipfile
import os
• zipfile: This module allows us to work with ZIP files, which will be used to create a
ZIP archive of the specified folder.
• os: This module provides functions for interacting with the operating system, such as
file path manipulation and directory traversal.
2. backupToZip(folder) Function:
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
• number = 1: Initializes a counter to keep track of the ZIP file version (e.g., if
folder_1.zip already exists, it will create folder_2.zip instead).
while True:
print(f'Checking {zipFilename}...')
if not os.path.exists(zipFilename):
break
number += 1
• The while loop checks if a ZIP file with the current number already exists in the
directory.
• zipFilename creates the filename using the folder name followed by number (e.g.,
FolderName_1.zip).
• os.path.exists(zipFilename): Checks if a file with the generated zipFilename exists. If
it does, the number is incremented to avoid overwriting existing ZIP files.
• zipfile.ZipFile(zipFilename, 'w') creates a new ZIP file for writing with the specified
filename (zipFilename).
newBase = os.path.basename(folder)
continue
backupZip.write(os.path.join(foldername, filename))
• os.walk(folder): Traverses through all directories, subdirectories, and files within the
folder.
• for filename in filenames: Loops through each file in the current folder.
• newBase = os.path.basename(folder): Extracts just the folder name from the folder
path.
• The if statement checks if the file is an existing ZIP file for the folder itself (to avoid
including it in the new backup ZIP).
backupZip.close()
print('Done.')
• backupZip.close(): Closes the ZIP file, ensuring all files are properly written to the
archive.
def main():
backupToZip("C:\\Users\\bhara\\Documents\\Jupyter\\Foldertobezipped")
if __name__ == "__main__":
main()
• This line checks if the script is being run directly (as opposed to being imported as a
module).
PROGRAM:
import zipfile
import os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
print(f'Checking {zipFilename}...')
if not os.path.exists(zipFilename):
break
number += 1
print(f'Creating {zipFilename}...')
newBase = os.path.basename(folder)
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
def main():
backupToZip("C:\\Users\\bhara\\Documents\\Jupyter\\Foldertobezipped")
if _name_ == "_main_":
main()
Output:
Done.