I am working in a directory with path being "C:\Downloads\Project" I have a folder "Insights" in "Project" (Project\Insights) folder which has multiple text files with names being "Text1.txt", "Text2.txt"..."Text30.txt". Every 10 text files are supposed to be zipped into a zip file into same "Insights" folder (...\Insights\zip1.zip).
How can this be done in Python?
When I tried zipping, text files are being stored with directory structure "...\Project\Insights\text1.txt" in zip file. But I don't want the files to be stored with any directory structure.
from zipfile import ZipFile
#dictionary of files and data in it (dummy data)
file_data={"C:\Downloads\Project\Insights\Text1.txt":"value1",
"C:\Downloads\Project\Insights\Text2.txt":"value2"
}
zipp = ZipFile('Insights//zip1.zip', 'w')
for k, v in file_data.items():
zipp.write(k)
zipp.close()
This snippet generates zip file with entire directory structure. But I want the text files alone
try this snippet:
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),
os.path.relpath(os.path.join(root, file),
os.path.join(path, '..')))
zipf = zipfile.ZipFile('Python.zip', 'w', zipfile.ZIP_DEFLATED)
zipdir('tmp/', zipf)
zipf.close()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.