Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why can't I zip a file in Python?

So I created a script in Python that takes a user specified file and zips it up as a zip file.

When I tried it out it doesn’t work my code complains how the path is not found I have tried so many different things and looked at a lot of tutorials about how to do this none work.

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import zipfile
FZ = 0
F = input("What file do you want zipped? ")
FZ = FZ + 1
with zipfile.ZipFile(("ZipFile", FZ, ".zip"), "w") as z:
    z.write(F)
input("Done! Press any key to quit... ")

What am I doing wrong?

>Solution :

It appears you are confused about how to build strings, based on this line:

with zipfile.ZipFile(("ZipFile", FZ, ".zip"), "w") as z:

If this were a print statement, doing print("ZipFile", FZ, ".zip") would correctly output something like ZipFile 1 .zip. However that’s a specific feature of how the print function works; in general, a tuple of strings does not magically get converted into just one long string. If you want to store a string, or pass one to a function, that looks like how you want, you’ll have to use one of the many existing ways to put a variable into a string. For example, as an f-string:

with zipfile.ZipFile(f"ZipFile{FZ}.zip", "w") as z:

In that case, if FZ was 1, the first argument would be passed as "ZipFile1.zip"

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading