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.
Related
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
I found out how to do it with this script:
import os, sys, shutil, glob
if not os.path.exists('Files'):
os.makedirs('Files')
source_dir = os.path.join(os.environ["HOMEPATH"], "Desktop")
dest_dir = 'Files'
try:
for root, dirnames, filenames in os.walk(source_dir):
for file in filenames:
(shortname, extension) = os.path.splitext(file)
if extension == ".txt" :
shutil.copy2(os.path.join(root,file), os.path.join(dest_dir,
os.path.relpath(os.path.join(root,file),source_dir)))
except FileNotFoundError:
pass
But, it only copies the files in the path and not the in sub-folders
So for example here it copies the desktop .txt files, but it does not copy the files in the folders.
Thanks, have a good day.
I am trying to find all the files with name ACC.txt in a given folder and its subfolder and then append them to create a new file i.e. output_file.txt. All the files are not in the working directory.
I have written the following code, but it is throwing a empty file.Please correct the code
import os
import shutil
BASE_DIRECTORY = r'E:\equity research\test_data'
with open('output_file.txt','wb') as wfd:
for dirpath, dirnames, filenames in os.walk(BASE_DIRECTORY):
for filename in filenames:
if filename == "ACC.txt":
fullPath = os.path.join(dirpath, filename)
with open(fullPath,'rb') as fd:
shutil.copyfileobj(fd, wfd)
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()
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()