-3

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:

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?

User121212
  • 13
  • 4
  • 2
    When you say "it doesn't work" can you explain what it does and what's wrong with what it does? – joanis May 12 '22 at 15:21
  • 3
    what happens when you run it? also I think this part should be a single string instead of a tuple of three strings: `("ZipFile", FZ, ".zip")` – Anentropic May 12 '22 at 15:22
  • 3
    Right, maybe you need `f"ZipFile{FZ}.zip"` instead of that tuple? – joanis May 12 '22 at 15:23
  • your problem is NOT zipfile module but you simply don't know how to work with strings - to create string with file name. You can't create single string using tuple `("ZipFile", FZ, ".zip")` - you have to use `f-string` like in previous comments `f"ZipFile{FZ}.zip"` or use `"ZipFile" + str(FZ) + ".zip"` – furas May 12 '22 at 15:45

1 Answers1

2

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"

Random Davis
  • 6,662
  • 4
  • 14
  • 24