指定したディレクトリをバックアップするスクリプト
# !/user/bin/env python # - Copeies an entire folder and its contents into # 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 use 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 += 1 # Create Zip file. print('Creating {}'.format(zipFilename)) backupzip = zipfile.ZipFile(zipFilename, 'w') # Walk the enter folder tree and compress the files in each folder. for foldername, subfolders, filenames in os.walk(folder): print('adding files in {}'.format(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: newBase = os.path.basename(folder) + '_' if filename.startswith(newBase) and filename.endswith('.zip'): continue backupzip.write(os.path.join(foldername, filename)) backupzip.close() print('done') def main(): backupToZip("1702") if __name__ == '__main__': main()