简体   繁体   中英

Python - automaticly zip specific folders/files

I have been getting into Python lately and have come across a problem wich i think i could solve using it. I have a USB stick with a lot of folders in there, the folders each contain the following:

/HTML5/
/Images/
foldername.html
foldername.ofp
preview.html
profile.xml

Now, i have to create a zip file of each folder, but only containing the Images folder and the profile.xml file. There is 40ish folders in there and there will be more in the future.

Here is the final code:

# Script to zip Foldername/Images/ and Foldername/profile.xml to Foldername.zip

import os
import zipfile

dirname = "D:\\testdir"

for schoen in os.listdir(dirname):
    print schoen
    myZipFile = zipfile.ZipFile(schoen+".zip", "w" )
    for f in os.listdir(os.path.join(dirname, schoen)):
        print f
        if f == "Profile.xml":
            print "Found profile.xml"
            myZipFile.write(schoen + "\\" + f, f)
        elif f == "Images":
            print "Found Images"
            myZipFile.write(schoen + "\\" + f, f)
    myZipFile.close()

Many thanks, Grootie

Instead of finding random code and trying to guess what it might mean and what you should change, why not look it up in the documentation?

The parameters to ZipFile.write are:

ZipFile.write(filename, arcname=None, compress_type=None)

So your code copies the file named profile.xml into the archive under the name images\\\\test.py . Is that really what you want? I doubt it. But I'm not sure what you do want. You need to figure that out, in terms you could explain to an idiot (because computers are idiots). Then the docs—or SO, if you get confused by the docs—can help you translate that explanation into the appropriate code.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM