2

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()
Dharman
  • 30,962
  • 25
  • 85
  • 135
vmedhe2
  • 237
  • 4
  • 19
  • well, your error message contradicts you, so I'd say you *think* the file is there, but it isn't, or you *think* python is looking in the right directory, but isn't. By the way: You have an indentation error. Your last line `zf.write(file)` needs to be indented. – Marcus Müller Sep 23 '15 at 16:37
  • Thanks, sorry for indent error its fine in the code, I will edit that. I know I have the file in that folder. So thats not it. – vmedhe2 Sep 23 '15 at 16:45
  • 1
    As I said, then Python is not looking in the folder you think it's looking in. – Marcus Müller Sep 23 '15 at 16:46
  • one thing to check... try printing out `src` and `path` in your real example and make sure they are the same... one is a raw string, the other is not above (and you have backslashes), in many cases they will be the same, but sometimes they will not... – Corley Brigman Sep 23 '15 at 16:52
  • You are right src and path are not the same. Path is correct though I will try that. – vmedhe2 Sep 23 '15 at 17:01

2 Answers2

2

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.

babbageclunk
  • 8,523
  • 1
  • 33
  • 37
1

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)
Marcus Müller
  • 34,677
  • 4
  • 53
  • 94