Python:无法创建Zip文件

时间:2015-07-14 18:12:26

标签: python-3.x zip

我只是从Python教程网站复制并粘贴了这段代码,但代码不起作用。缺少什么?我使用的是3.4.3版本。谢谢。

import zipfile

# Create zip file
print("Creating zip archive")
zf = zipfile.ZipFile("python_zip_file.zip", mode = "w")

try:
    # Add file to our zip
    zf.write("zippy2.py")
finally:
    print("closing")
    zf.close()

Traceback (most recent call last):
  File "/Users/Cindy/Documents/Python/Zip.py", line 9, in <module>
    zf.write("zippy2.py")
  File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/zipfile.py", line 1326, in write
    st = os.stat(filename)
FileNotFoundError: [Errno 2] No such file or directory: 'zippy2.py'

2 个答案:

答案 0 :(得分:0)

# Add file to our zip
zf.write("zippy2.py")

您应该在文件夹中有一个名为zippy2.py的文件。

由于您刚刚复制了代码,因此您可能没有代码中提到的文件。创建文件 zippy2.py在同一个文件夹中并检查。

答案 1 :(得分:0)

尝试用这个来学习..

#!/usr/bin/env python
import zipfile 

print("Creating zip archive")
zip = zipfile.ZipFile(‘Archive.zip’, ‘w’) #Archive is the name of the zip file
zip.write(‘file.txt’)  #file.txt should be in the current working directory
zip.write(‘file1.txt’) #file1.txt too
zip.close()