zoukankan      html  css  js  c++  java
  • Python学习笔记组织文件之将一个文件夹备份到一个zip文件

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

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

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

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

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

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

      示例代码:

    #! 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')
    

      运行结果:

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

  • 相关阅读:
    Android 压力测试工具Monkey
    解决maven的依赖总是无法下载完成
    JDBC连接数据库(二)
    JDBC连接数据库(一)
    webdriver js点击无法点击的元素
    多线程Java面试题总结
    PHP unset销毁变量并释放内存
    ThinkPHP函数详解:D方法
    PHP 函数:intval()
    ThinkPHP 模板显示display和assign的用法
  • 原文地址:https://www.cnblogs.com/lirongyang/p/9655971.html
Copyright © 2011-2022 走看看