LaoDa581
LaoDa581

Reputation: 613

What is correct way to use zipfile to archive each file?

Now I need to archive files separately under target path.

Here is the tree.

C:\Users\User\Downloads\
|   file_1.py
|   file_2.py
|   file_3.py
|
\---Folder
        file_4.py
        file_5.py

Here is my code.

import os
import zipfile


def archive(file_path):
  for file_name in os.listdir(file_path):
    file = os.path.join(file_path, file_name)
    if os.path.isfile(file):
      with zipfile.ZipFile(f'{file}.zip', 'w') as zip:
        zip.write(file)
      os.remove(file)

archive(r'C:\Users\User\Downloads')

I can actually archive file_1.py, file_2.py, and file_3.py separately. However, I opened file_1.zip and saw that not only the file is zipped but also contains the full path.

What is correct way to use zipfile to archive each file?

Upvotes: 3

Views: 139

Answers (1)

001
001

Reputation: 13533

You can use the write functions 2nd parameter to specify the name of the file inside the archive. Just pass the file name to that. Also, use os.walk() to process all folders:

def archive(folder):
    for root, dirs, files in os.walk(folder):
        for file in files:
            full_path = os.path.join(root, file)
            zip_file = os.path.join(root, f'{file}.zip')
            with zipfile.ZipFile(zip_file, 'w') as zip:
                zip.write(full_path, file)
            # Delete original
            os.remove(full_path)

Upvotes: 1

Related Questions