Python学习笔记组织文件之将一个文件夹备份到一个zip文件

 随笔记录方便自己和同路人查阅。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  假定你正在做一个项目,它的文件保存在C:\AlsPythonBook 文件夹中。你担心工作会丢失,所以希望为整个文件夹创建一个ZIP 文件,作为“快照”。你希望保存

不同的版本,希望 ZIP 文件的文件名每次创建时都有所变化。例如 AlsPythonBook_1.zip、AlsPythonBook_2.zip、AlsPythonBook_3.zip,等等。你可以手工完成,

但这有点烦人,而且可能不小心弄错ZIP 文件的编号。运行一个程序来完成这个烦人的任务会简单得多。

#------------------------------------------------我是可耻的分割线-------------------------------------------

  示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#! python 3
# -*- coding:utf-8 -*-
# Autor: Li Rong Yang
#a ZIP file whose filename increments
import zipfile, os
 
def backupToZip(folder):
    # Backup the entire contents of "folder" into a zip file.
 
    folder = os.path.abspath(folder) # make sure folder is absolute
 
    # Figure out the filename this code should used based on
    # what files already exist.
    number = 1
    while True:
        zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
        if not os.path.exists(zipFilename):
            break
        number = number + 1
 
    # Create the zip file.
    print('Creating %s...' % (zipFilename))
    backupZip = zipfile.ZipFile(zipFilename, 'w')
 
    # Walk the entire folder tree and compress the files in each folder.
    for foldername, subfolders, filenames in os.walk(folder):
        print('Adding files in %s...' % (foldername))
        # Add the current folder to the ZIP file.
        backupZip.write(foldername)
 
        # Add all the files in this folder to the ZIP file.
        for filename in filenames:
            if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
                continue # don't backup the backup ZIP files
            backupZip.write(os.path.join(foldername, filename))
    backupZip.close()
    print('Done.')
 
backupToZip('d:\\quiz')

  运行结果:

  会把传入的路径中所有内容,备份到当前工作目录中

posted @   李荣洋  阅读(356)  评论(0编辑  收藏  举报
编辑推荐:
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示