简体   繁体   English

为什么我不能 zip Python 中的文件?

[英]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.因此,我在 Python 中创建了一个脚本,该脚本采用用户指定的文件并将其压缩为 zip 文件。

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?我究竟做错了什么?

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 .如果这是一条print语句,执行print("ZipFile", FZ, ".zip")将正确地 output 类似于ZipFile 1.zip However that's a specific feature of how the print function works;然而,这是print function 工作原理的一个特定功能; 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 .如果你想存储一个字符串,或者将一个字符串传递给 function,这看起来像你想要的那样,你将不得不使用许多现有方法中的一种将变量放入字符串中。 For example, as an f-string:例如,作为 f 字符串:

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"在那种情况下,如果FZ1 ,第一个参数将作为"ZipFile1.zip"传递

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM