简体   繁体   中英

Python - Zipping a directory

This code currently creates a zip file on the same destination the Python script is executed, and attempts to populate the zip with the contents on "Documents and Settings\\Owner". However, it keeps trying to copy across ntuser.dat and NTUSER.dat which gives me an error: [Errno 13] Permission denied: 'C:\\\\Documents and Settings\\\\Owner\\\\NTUSER.DAT'

How can I skip those two files to allow the zip process to continue? I've attempted to identify if a ntuser files is trying to be copied, and just pass over the error, but has no effect.

import os, zipfile, getpass

try:
    user= getpass.getuser()
    zf = zipfile.ZipFile(user + ".zip", "w", zipfile.ZIP_DEFLATED)
    directory = "C:\\Documents and Settings\Owner"
    for dirname, subdirs, files in os.walk(directory):
        zf.write(dirname)
        for filename in files:
            if "NTUSER" in filename:
                pass
            zf.write(os.path.join(dirname, filename))
except IOError as e:
    print e
    pass
zf.close()

Your code doesn't do anything when you find a matching file:

for filename in files:
    if "NTUSER" in filename:
        pass
    zf.write(os.path.join(dirname, filename))

pass is a no operation statement. Python will just continue to the next line, which writes the file to the ZIP.

If you wanted to skip those files, use continue instead:

for filename in files:
    if "NTUSER" in filename:
        continue
    zf.write(os.path.join(dirname, filename))

This tells Python to skip the rest of the loop body and go to the next iteration instead, thus skipping the zf.write() call.

A pass statement is only useful in places where the Python grammar requires there to be a line. For example, if you wanted to ignore a specific exception you'd write:

try:
    # code that can raise an exception
except SpecificException:
    pass

because you have to write something in the except block; pass fits that 'something' nicely.

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