-2

i'm trying to do a program here i need to compress some files, but i want it to stop when the file doesn't exist. The code works, but the thing is that it compresses the file anyway, what i mean is that the program outputs the error but compress a file with that name (an empty file)

if someone could help it would be wonderful :)

import sys, zipfile

def compress (file):
    try:
        zf = zipfile.ZipFile(file + '.zip', mode='w')
        zf.write(file, compress_type=zipfile.ZIP_DEFLATED)
        zf.close()
    except OSError:
        print("The file "+ file + " doesnt exist!")
        #erro.value = 1

if __name__ == "__main__":
    compress(sys.argv[1])
DavidG
  • 24,279
  • 14
  • 89
  • 82
Kuk Apep
  • 15
  • 4
  • 1
    Check if the file exists first. See https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-using-python – AlG Nov 08 '17 at 13:13

1 Answers1

1

From Python documentation:

If the file is created with mode 'w', 'x' or 'a' and then closed without adding any files to the archive, the appropriate ZIP structures for an empty archive will be written to the file.

So use

if os.path.exists(file)

to check if the file exists, before

zf = zipfile.ZipFile(file + '.zip', mode='w')
Ammar Alyousfi
  • 4,112
  • 5
  • 31
  • 42