Python Forum
Failing to Zip files - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Failing to Zip files (/thread-31264.html)



Failing to Zip files - tester_V - Dec-01-2020

Hi, I'm trying to find files that have digits in a file name.
then I'd like to zip files to another directory.
My code finds the files I want and moves them to a directory I want but not as ZIP files Sad .
Any help will be appreciated.

from zipfile import ZipFile
import os
import glob
import os.path
 
pth = 'c:\\02'
zout= 'C:\\0001\\'
for fname in glob.glob('C:\\02\\*[0-9].*'):
    basename = os.path.basename(fname)
    fz = zout+basename
    with ZipFile(fz,'w') as zip: 
        zip.write(fz)



RE: Failing to Zip files - bowlofred - Dec-01-2020

Do you want to write them all into one zipfile or each one into separate zipfiles?

You set pth, but then never use it, with c:\\02 hardcoded.

Line 11 is where you name the zipfile.
Line 12 is where you name the file you want to put in the zipfile.

You've used fz for both of these, which is incorrect. Probably you want to write the fname to the zip file.


RE: Failing to Zip files - tester_V - Dec-01-2020

Thanks bowlofred!

I tried your suggestions.
Still the script only copies files not zipps then up.
I actually tried to open one of the copied files, they all have extensions '.TXT' but it is not a'.TXT' file. I cannot really open it up. SO the script does something to the files.
here is a new version of the script:
from zipfile import ZipFile
import os
import glob
import os.path

zout= 'C:\\0001\\'
for fname in glob.glob('C:\\02\\*[0-9].*'):
    print (fname)
    basename = os.path.basename(fname)
    fz = zout+basename
    print (fz)
    with ZipFile(fz,'w') as zip: 
        zip.write(fname)



RE: Failing to Zip files - bowlofred - Dec-01-2020

How are you trying to open it? It's a zipfile, but you didn't change the name, so it's got the same name as it had before. You should name the zipfile with a .zip ending.

for fname in glob.glob('C:\\02\\*[0-9].*'):
    print (fname)
    basename = os.path.basename(fname)
    fz = zout+basename
    print (fz)
    zipname = os.path.splitext(fz)[0] + ".zip"  # Change name to have .zip extension
    with ZipFile(zipname,'w') as zip:           # Use .zip name for zipfile
        zip.write(fname)



RE: Failing to Zip files - tester_V - Dec-01-2020

to bowlofred:
Thanks man!
I actually come up with my own solution.
It is not as short as yours... Smile

zout= 'C:\\0001\\'
for fname in glob.glob('C:\\02\\*[0-9].*'):
    basename = os.path.basename(fname)
    just_n = os.path.splitext(basename)[0]   
  
    fz = zout+just_n+'.zip'

    with ZipFile(fz,'w') as zip: 
        zip.write(fname,arcname=basename)
        print (zip)
I really appreciate your help!