Zip and unzip files with python

Its easy to zip and unizip files with python built in zipfile module

For this we have to get the file location list . which files we wan to zip. we can use python glob to get the path

current example structure

├── file_location_list.py
└── NewFolder
    ├── image.png
    └── text.txt

import glob
files=glob.glob("NewFolder/*")
print(files)



It will print the result like this

['NewFolder/image.png', 'NewFolder/text.txt']

So it print all the file location in the NewFolder

In the previous example we got the file location list. Now we will get the list files and create a zip file


import glob
files=glob.glob("NewFolder/*")
print(files)


from zipfile import ZipFile

# Create a ZipFile object in write mode
with ZipFile('NewZipFile.zip', 'w') as z:
    for file in files:
        z.write(file)

print('successfully created zip file!')



Now unzip the files


from zipfile import ZipFile

# replace NewZipFile.zip with your zip file which you want to unzip
with ZipFile('NewZipFile.zip', 'r') as z:
    z.extractall()

print('Successfully unzipped files')



Related Posts

Print with python f string format
July 3, 2024

We use make the python print more wonderful with f string (formatted string) x=1 y=2 z=x+y print(f’result {x}+{y}={z}’) Copy Code this will print We can make it more wonderful directly adding expression x=1 y=2 print(f'{x} times {y} is {x * y}’) Copy Code We can also set the decimal places in the print number = […]

Check if a key exist or not in a python dictionary
July 3, 2024

We can check it with “in” operator and “get()” method In operator here returns the value True or False For example dictionary={“one”:1, “two”:2} if “two” in dictionary: print(“two exist in the dictionary”) Copy Code The get() method returns the value if that key exists. If not exists it returns None dictionary_data={“one”:1, “two”:2} #Here the key […]

Find out median of a list with python
July 3, 2024

Python has wonderful built-in library “statistics” We can find out the median of a list with this library easily with less code import statistics List = [1,2,3,4,5,6,7,8,9,10] result= statistics.median(List) print(result) Copy Code We can also generate list randomly with random module List = [randint(1, 101) for _ in range(50)] this code create a list of […]