Home > Software engineering >  Zipping a list of folders with Python
Zipping a list of folders with Python

Time:04-30

everyone. I'm really new to Python, so I need some help here. I have a list of folders names inside a .CSV file. All these folders are inside the same path. I need to zip them individually (each one needs to become a .ZIP file, maintaining its own original name) and, after zipping, delete the original folders.

Tried some things here, but had no success :(

I read about zipfiles, os.walk, import csv, but I can't get these things together.

Can someone help me with this one?

The code is here. I'm really sorry, it probably makes no sense as it is. I'm really a begginer :(

import os
import zipfile
import csv
import sys

os.chdir('dir')
files='dir'

for i in range (len(files)):
    with zipfile.ZipFile(files(i) '.zip', 'w') as zipMe:
        zipMe.write(files[i], compress_type=zipfile.ZIP_DEFLATED)

CodePudding user response:

  1. The read_csv() function is called to open the CSV file and read the directory names from the CSV into a list named dir_names.
  2. The read_csv() function calls the zip_dirs() function and passes the dir_names list containing the directory names. The zip_dirs() function zips each directory into a zip file and saves it.
  3. The zip_dirs() function calls the delete_dirs() function and it deletes the original directories.
import os
import csv
import zipfile

dir_names = []
zip_out = 'dirs.zip' 
dir_csv = 'dir_names.csv'
parent_dir = 'dir-to-zip/'

# delete directories
def delete_dirs(dir_names):
    for dir in dir_names:
        os.rmdir(parent_dir   dir)

# zip directories
def zip_dirs(dir_names):
    for dir in dir_names:
        zip_process = zipfile.ZipFile(dir   '.zip', "w", zipfile.ZIP_DEFLATED)
        zip_process.write(parent_dir   dir)
    zip_process.close()
    delete_dirs(dir_names)

# read the directory names from csv file
def read_csv():
    with open(dir_csv, 'r') as f:
        csv_reader = csv.reader(f, delimiter=',')
        for row in csv_reader:
            dir_names.append(row[0])
    zip_dirs(dir_names)        

read_csv()

CSV Input:

| ------| 
| dir1  | 
| dir2  | 
| dir3  | 
| dir4  | 

Directory Structure:

./dir-to-zip
    /dir1
    /dir2
    /dir3
    /dir4

CodePudding user response:

Using the shutil library in python

#importing libraries 

import pandas as pd
import os
import shutil
### *****below directories are simply examples; please set your own directories*****

folder_directory = 'D:\\Zip test' #setting directory where original folders are present

os.chdir(folder_directory) #changing current directory so that zip files are formed in the original directory

df = pd.read_csv(r'C:\Users\sahaa\Downloads\folder_names.csv') # reading the csv file with folder names

fol_nam = df['Folder Names'].tolist() # creating a list of the folders to be zipped which are present under the column 'Folder Names' in the CSV.
 
for i in fol_nam: # for loop
    shutil.make_archive(i, 'zip', 'D:\\Zip test'   '\\'   i) # zipping each folder and keeping the nomenclature same
    shutil.rmtree('D:\\Zip test'   '\\'   i) # deleting original folder after zipping

CodePudding user response:

Try this

└───main_dir
    ├───dir01
    ├───dir02
    └───dir03

....

import shutil
import os


def compress_directory(source_dir, output_filename, kind='zip'):
    shutil.make_archive(output_filename, kind, source_dir)


main_dir = r'S:\repo\tools\main_dir'

# list sub folders
all_dirs = [os.path.join(*[main_dir, sub_dir]) for sub_dir in os.listdir(main_dir)]

# zip sub dirs
for sub_dir in all_dirs:
    compress_directory(sub_dir, sub_dir)
    # remove sub directory
    shutil.rmtree(sub_dir)

# zip main dir
compress_directory(main_dir, main_dir)
# remove main directory
shutil.rmtree(main_dir)

...

└───main_dir.zip
    ├───dir01.zip
    ├───dir02.zip
    └───dir03.zip
  • Related