2

I have tried to zip log files that I have created, but nothing is written! Code:

    def del_files():
        '''Adapted from answer @ http://stackoverflow.com/questions/7217196/python-delete-old-files by jterrace'''
        dir_to_search = os.path.join(os.getcwd(),'log')
        for dirpath, dirnames, filenames in os.walk(dir_to_search):
            for file in filenames:
                curpath = os.path.join(dirpath, file)
                log(curpath)
                if curpath != path:
                    log("Archiving old log files...")
                    with zipfile.ZipFile("log_old.zip", "w") as ZipFile:
                        ZipFile.write(curpath)
                        ZipFile.close()
                        log("archived")
Dharman
  • 30,962
  • 25
  • 85
  • 135
Restioson
  • 131
  • 1
  • 10

1 Answers1

1

For one thing, you are overwriting the output zip file on each iteration:

with zipfile.ZipFile("log_old.zip", "w") as ZipFile:

mode "w" means to create a new file, or truncate an existing file. Probably you mean to append to the zip file, in which case it can be opened for append by using mode "a". Or you could open the zip file outside of the outer for loop.

Your code should result in log_old.zip containing a single file - the last one found by os.walk().

Opening the archive outside of the main loop is better since the file will only be opened once, and it will be closed automatically because of the context manager (with):

with zipfile.ZipFile("log_old.zip", "w") as zf:
    dir_to_search = os.path.join(os.getcwd(), 'log')
    for dirpath, dirnames, filenames in os.walk(dir_to_search):
        for file in filenames:
            curpath = os.path.join(dirpath, file)
            zf.write(curpath)
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • When I used this, it resulted in a zipfile with a folder hierachy like this: `Users\*User*\Documents\GitHub\Game\log` and had 1 file. I want to archive all my files except the one being written to – Restioson May 16 '15 at 12:29
  • From which directory did you execute the above code? It should only archive those files contained in the `log` subdirectory of the current directory, with the archive being written to the current directory. That means that you must have run it from `\Users\*USER*\Documents\GitHub\Game\log_old.zip\Users\Cael\Documents\GitHub\Gam‌​e`. – mhawke May 16 '15 at 12:48