vmedhe2
vmedhe2

Reputation: 237

Python:writing files in a folder to zipfile and compressing it

I am trying to zip and compress all the files in a folder using python. The eventual goal is to make this occur in windows task scheduler.

import os
import zipfile

src = ("C:\Users\Blah\Desktop\Test")
os.chdir=(src)
path = (r"C:\Users\Blah\Desktop\Test")
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
      zf.write(file)

Now when I run this script I get the error:

WindowsError: [Error 2] The system cannot find the file specified: 'test1.bak'

I know it's there since it found the name of the file it can't find.

I'm wondering why it is not zipping and why this error is occurring.

There are large .bak files so they could run above 4GB, which is why I'm allowing 64 bit.

Edit: Success thanks everyone for answering my question here is my final code that works, hope this helps my future googlers:

import os
import zipfile
path = (r"C:\Users\vikram.medhekar\Desktop\Launch")
os.chdir(path)
dirs = os.listdir(path)
zf = zipfile.ZipFile("myzipfile.zip", "w", zipfile.ZIP_DEFLATED,allowZip64=True)
for file in dirs:
  zf.write(os.path.join(file))
zf.close()

Upvotes: 2

Views: 1892

Answers (2)

babbageclunk
babbageclunk

Reputation: 8731

os.listdir(path) returns names relative to path - you need to use zf.write(os.path.join(path, file)) to tell it the full location of the file.

Upvotes: 2

Marcus Müller
Marcus Müller

Reputation: 36346

As I said twice in my comments: Python is not looking for the file in the folder that it's in, but in the current working directory. Instead of

zf.write(file)

you'll need to

zf.write(path + os.pathsep + file)

Upvotes: 1

Related Questions