Appending (.txt) file to Zip File

1113
3
Jump to solution
11-29-2016 02:08 PM
JaredPilbeam1
Occasional Contributor

Hi,

There's a similar thread here but it's sort of left unanswered: Adding extra files to a zip? 

I have this script to append to a zip file archive:

import zipfile

print 'appending to the archive'
zf = zipfile.ZipFile('W:\Data\WillCounty_AddressPoint.zip', mode='a')
try:
    zf.write('Z:\Jared\Disclaimer - Final.txt')
finally:
    zf.close()‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

The problem is that I included the whole file path on line 6, so the whole folder (Jared) was appended to the zip and not just the (.txt) file.

If I exclude the path and type only the file name it can't be found? 

Is there a way to just append the (.txt) file to the zip file?

0 Kudos
1 Solution

Accepted Solutions
DarrenWiens2
MVP Honored Contributor

The optional second argument is where you specify an alternate name, if needed:

zf.write(r'Z:\Jared\Disclaimer - Final.txt','Disclaimer - Final.txt')‍‍

... or better yet:

import zipfile, os
...
path = r'Z:\Jared\Disclaimer - Final.txt'
zf.write(path,os.path.basename(path))

^ also, be careful how you write your paths. Should use 'r','/', or '\\'.

View solution in original post

3 Replies
DarrenWiens2
MVP Honored Contributor

The optional second argument is where you specify an alternate name, if needed:

zf.write(r'Z:\Jared\Disclaimer - Final.txt','Disclaimer - Final.txt')‍‍

... or better yet:

import zipfile, os
...
path = r'Z:\Jared\Disclaimer - Final.txt'
zf.write(path,os.path.basename(path))

^ also, be careful how you write your paths. Should use 'r','/', or '\\'.

JaredPilbeam1
Occasional Contributor

Thanks Darren. The second option worked problem-free. 

One other thing unrelated; when running the same block of code for a different file to be appended to, do I really need to repeat the same block in it's entirety? For example, I want to appended the same (.txt) file to a different zip file, so I simply repeated it (starting on line 14). See code below: 

0 Kudos
DarrenWiens2
MVP Honored Contributor

You can avoid repeating blocks of code by using functions and loops, like below.

def append2Zip(zipfolder,path):
  print 'Appending to ' + zipfolder
  zf = zipfile.ZipFile(zipfolder,mode='a')
  try:
    zf.write(path,os.path.basename(path))
  finally:
    zf.close()

path = r'Z:\Jared\Disclaimer - Final.txt'
zipfolders = [r'W:\Data\WillCounty_AddressPoint.zip',r'W:\Data\WillCounty_Street.zip'] # list of zip folders

for zipfolder in zipfolders: # loop through zipfolders
  append2Zip(zipfolder,path) # call function above