0

I've seen a few responses near what I'm after, yet my code is still not working. I've peppered it with print statements to see what each stage is doing and this (theoretically!) is actually what I'm after, yet I'm not getting the result.

Trying to FOR LOOP multiple files to a ZIP archive using WITH statement (yet no luck)

def files_rezip():
    num = 1
    for i in os.listdir():
        x = os.path.splitext(i)
        if 'temp' in x[0]:
            new_dir = os.getcwd() + '\\' + i

# (ABOVE IS CONTEXT) - BELOW IS WHERE THE ISSUE IS...
            with zipfile.ZipFile(os.getcwd() + '\\' + 'new_zip_'+ str(num) + '.zip', 'w') as new_file:
                for nf in os.listdir(new_dir):
                    new_file.write(nf)

            num += 1
    print('Task Complete')

I've also tried:

new_file.write(new_dir + '\\' + nf)

The issue seems to be in the line:

new_file.write(nf)

I've tried the above - but this is just the file name without a path

This does provide the absolute path and helps it locate the files correctly - but this also causes the zip to recreate the whole file path IN the ZIP file?!

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Matt
  • 159
  • 1
  • 8
  • 1
    `nf` is the path to a file. Are you trying to write path strings into the zip file, or are you trying to write the contents of the file referred to be the path `nf`? – John Zwinck Jun 08 '19 at 04:26
  • Just want it to iterate through the folder and call the files individually and write them to the zip archive (created in the WITH statement). Really don't want the path added too :) – Matt Jun 08 '19 at 04:53
  • Possible duplicate of [python/zip: How to eliminate absolute path in zip archive if absolute paths for files are provided?](https://stackoverflow.com/questions/16091904/python-zip-how-to-eliminate-absolute-path-in-zip-archive-if-absolute-paths-for) – Gino Mempin Jun 08 '19 at 05:09

1 Answers1

0

Just figured it out (have to say.. not seen this suggest on any tutorials I've come across!!)

with zipfile.ZipFile(os.getcwd() + '\\' + 'new_zip_'+ str(num) + '.zip', 'w') as new_file:
    for nf in os.listdir(new_dir):
        new_file.write(new_dir + '\\' + nf, nf) # n.b. extra parameter

The solution is a 2nd parameter on the WRITE statement, explicitly stating and passing the intended file name.

Script now works - thanks guys!

martineau
  • 119,623
  • 25
  • 170
  • 301
Matt
  • 159
  • 1
  • 8