Zip all the files of a folder in the same folder - python

I am trying to zip all the files from a folder and places it in the same folder. Below is my code:
import os as __os
import zipfile
def zipdir(path, ziph):
for root, dirs, files in __os.walk(path):
for file in files:
print(file)
ziph.write(__os.path.join(root, file))
if __name__ == '__main__':
zip_name = 'test.zip'
working_directory = "C:\\Users\\Admin\\Downloads\\gaz"
archive_name = __os.path.join(working_directory, zip_name)
with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
zipdir(working_directory + '', zipf)
I am trying to create zip of all the files inside a folder. I am expecting the code to create a zip in the same folder. Its going into infinite.

I don't really see an endless loop but you're including the newly created test.zip (empty) to the archive of the same name.
It would be better to check file before adding it to the archive:
def zipdir(path, ziph):
for root, dirs, files in __os.walk(path):
for file in files:
if file != zip_name:
print(file)
ziph.write(__os.path.join(root, file))

The zipdir() funciton is calling itself recursively, resulting in the infinite loop. Try zipf.write(). That function adds a file to a zip archive.
with zipfile.ZipFile(archive_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in __os.walk(working_directory):
for file in files:
if os.path.samefile(archive_path, os.path.join(root, file)):
continue
zipf.write(__os.path.join(root, file))
Edit: Check if archive_name file is located in working_directory

Related

Zip multiple, specific folders into one zip file

I have a bunch of folders full of data and I need specific ones to be sent to a zip folder. I can move them with a batch file but it does not automatically zip and then I have redundancy. I also tried a solution I saw.
import os
import zipfile
def zipit(folders, zip_filename):
zip_file = zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED)
for folder in folders:
for dirpath, dirnames, filenames in os.walk(folder):
for filename in filenames:
zip_file.write(
os.path.join(dirpath, filename),
os.path.relpath(os.path.join(dirpath, filename),
os.path.join(folders[0], '../..')))
zip_file.close()
folders = [
"\Users\andria.baunee\Desktop\New folder",
"\Users\andria.baunee\Desktop\New folder (2)",
"\Users\andria.baunee\Desktop\New folder (3)"]
zipit(folders, "\Users\andria.baunee\Desktop\hooray.zip")
Nothing seemed to happen.

compress with python but file is empty?

I'm trying to compress a folder with all files inside it
but I get the compressed file empty
Im using this code
import os
import zipfile
def zipdir(path, ziph):
# ziph is zipfile handle
for root, dirs, files in os.walk(path):
for file in files:
ziph.write(os.path.join(root, file))
if __name__ == '__main__':
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()

Getting the correct directory structure using Zipfile with Python

I have a directory structure that is like /level1/level2/level3/level4/level5 and in level5 I have .json files I want to replace with zipped up versions so from
/level1/level2/level3/level4/level5/{file1.json, file2.json, file3.json} to
/level1/level2/level3/level4/level5/{file1.zip, file2.zip, file3.zip}
However my code generates the zip files in the folder where the script is, which is level 3, resulting in /level1/level2/[level3]{file1.zip, file2.zip, file3.zip}/level4/level5/{file1.json, file2.json, file3.json}
In addition if I unzip the file I get the entire directory structure instead of just the file. For example if I unzip file1.zip I get /level1/level2/[level3]{(/level1/level2/level3/level4/level5/file1.json), file2.zip, file3.zip}/level4/level5/{file1.json, file2.json, file3.json}
I've tried different arguments but I'm not sure how to get the result I want. How can I accomplish this?
This is my code currently
path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
level4, level5)
for root, dirs, files in os.walk(path, topdown=True):
print('This is root: ', root)
for file in files:
zf = zipfile.ZipFile(
'{}.zip'.format(file[:-5]), 'w',
zipfile.ZIP_DEFLATED)
zf.write(os.path.join(root, file))
zf.close()
You should create the zip file with the root path joined so that the zip file will be created where the JSON file is, and when writing the JSON file into the zip file, use the writestr method instead of write so that you can name the file with the path name you want, which in this case is just the file name with no path name at all:
for root, dirs, files in os.walk(path, topdown=True):
print('This is root: ', root)
for file in files:
zf = zipfile.ZipFile(os.path.join(root, '{}.zip'.format(file[:-5])), 'w', zipfile.ZIP_DEFLATED)
zf.writestr(file, open(os.path.join(root, file)).read())
zf.close()

How to copy the entire file into a zip file

I want to put a file in every file of .txt, .mp3, and mp4 files.
import zipfile
import os
path = "G:"
file_zip = zipfile.ZipFile(path+'\\archive.zip', 'w')
for folder, subfolders, files in os.walk(path):
for file in files:
if file.endswith('.jpg,.txt,.mp3,.mp4'):
file_zip.write(os.path.join(folder, file), os.path.relpath(os.path.join(folder,file), path), compress_type = zipfile.ZIP_DEFLATED)
file_zip.close()
When I open the zip file, the zip file is empty!
Try changing:
if file.endswith('.jpg,.txt,.mp3,.mp4'):
to:
if file.endswith(('.jpg', '.txt', '.mp3', '.mp4')):

Create a zip file from a directory, but not his fullpath

Im trying to create a zipfile with the content of a folder ( some dirs and files ) using the code belllow:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
zip.write(os.path.join(root, file))
zip.close()
But after the code runs, when i check the zip file, the zip file, instead having the content of the folder "folderToZip" ( ex: f1,f2,f2, a.txt,b.txt,c.txt ) it have the full path of the variable path.
So, the question is, how can i create a zipfile based on a folder content, but not his fullpath ?
write takes a second optional parameter arcname, which when specified will provide the name for the file stored. Use that to specify the name you want.
If you only want the filename:
import zip,os
path = "c:\\tester\\folderToZip"
zip = zipfile.ZipFile("zippedFolder.zip", "w")
for root, dirs, files in os.walk(path):
for file in files:
filename = os.path.join(root, file)
zip.write(filename, filename)
zip.close()

Categories

Resources