Python学習ノート組織ファイルフォルダをzipファイルにバックアップ
2307 ワード
随筆の記録は自分と同行者が調べるのに便利だ.
#------------------------------------------------------------------------------------------------------------
プロジェクトをしていると仮定し、そのファイルはC:AlsPythonBookフォルダに保存されます.仕事がなくなるのではないかと心配しているので、フォルダ全体に「スナップショット」としてZIPファイルを作成したいと思っています.君は保存したい
バージョンによっては、ZIPファイルのファイル名が作成されるたびに変化することが望ましい.例えばAlsPythonBook_1.zip、AlsPythonBook_2.zip、AlsPythonBook_3.zip、など.手作りでできますが、
しかし、これはちょっとうるさいし、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')
実行結果:
入力されたパスのすべてのコンテンツが、現在の作業ディレクトリにバックアップされます.