亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

带有示例的 Python ZIP 文件

Python 允许您快速创建 zip/tar 档案。

以下命令将压缩整个目录

shutil.make_archive(output_filename, 'zip', dir_name)

以下命令可让您控制要归档的文件

ZipFile.write(filename)

以下是在 Python 中创建 Zip 文件的步骤

步骤 1) 要从 Python 创建存档文件,请确保您的导入语句正确且有序。这里存档的导入语句是 from shutil import make_archive

代码说明

步骤 2) 存档文件制作完成后,您可以右键单击该文件并选择操作系统,它会在其中显示您的存档文件,如下所示

现在您的 archive.zip 文件将出现在您的操作系统(Windows 资源管理器)中

步骤 3) 当你双击文件时,你会看到里面的所有文件的列表。

第 4 步) 在 Python 中,我们可以更好地控制存档,因为我们可以定义要包含在存档下的特定文件。在我们的例子中,我们将在存档 “guru99.txt” 下包含两个文件 和“guru99.txt.bak”。

代码说明

当您执行代码时,您可以看到在面板右侧创建了名为“guru99.zip”的文件

注意 :这里我们没有像“newzip.close”那样“关闭”文件,因为我们使用“With”范围锁定,所以当程序超出这个范围时,文件将被清理并自动关闭。

第 5 步) 当您 -> 右键单击​​文件 (testguru99.zip) 并 -> 选择您的操作系统(Windows 资源管理器) ,它将显示文件夹中的存档文件,如下所示。

当您双击文件“testguru99.zip”时,它会打开另一个窗口,这将显示其中包含的文件。

这是完整的代码

Python 2 示例

import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive

def main():
# Check if file exists
	if path.exists("guru99.txt"):
# get the path to the file in the current directory
	src = path.realpath("guru99.txt");
# rename the original file
	os.rename("career.guru99.txt","guru99.txt")
# now put things into a ZIP archive
	root_dir,tail = path.split(src)
    shutil.make_archive("guru99 archive", "zip", root_dir)
# more fine-grained control over ZIP files
	with ZipFile("testguru99.zip","w") as newzip:
	newzip.write("guru99.txt")
	    newzip.write("guru99.txt.bak")
if __name__== "__main__":
	  main()

Python 3 示例

import os
import shutil
from zipfile import ZipFile
from os import path
from shutil import make_archive

    # Check if file exists
       if path.exists("guru99.txt"):
    # get the path to the file in the current directory
        src = path.realpath("guru99.txt");
    # rename the original file
        os.rename("career.guru99.txt","guru99.txt")
    # now put things into a ZIP archive
        root_dir,tail = path.split(src)
        shutil.make_archive("guru99 archive","zip",root_dir)
    # more fine-grained control over ZIP files
        with ZipFile("testguru99.zip", "w") as newzip:
            newzip.write("guru99.txt")
            newzip.write("guru99.txt.bak")

总结


Python

  1. 如何开始使用 Python?
  2. Python 文件 I/O
  3. Java BufferedReader:如何通过示例在 Java 中读取文件
  4. Python String strip() 函数与示例
  5. 带有示例的 Python 字符串计数()
  6. 带有示例的 Python round() 函数
  7. 带有示例的 Python map() 函数
  8. Python Timeit() 与示例
  9. 集合中的 Python 计数器示例
  10. 带有示例的 Python 列表计数()
  11. Python 列表 index() 与示例
  12. Python - 使用 C 进行扩展编程