我是编程新手。我正在尝试使用CH Swaroop的“Byte of Python”来学习Python。一个例子是创建一个程序,它将一些文件从一个目录备份到另一个目录,并将它们压缩成.zip格式。不幸的是,他提供的示例仅在您恰好是linux / unix用户时才有用。对于Windows用户,他只说“Windows用户可以使用Info-Zip程序”,但没有进一步详细说明。这是他提供的代码......
#!/usr/bin/python
# Filename : backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = [r'C:\Users\ClickityCluck\Documents']
# 2. The backup must be stored in a main backup directory
target_dir = r'C:\Backup'
# 3. Zip seems good
# 4. Let's make the name of the file the current date/time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.zip'
# 5. We use the zip command to put the files in a zip archive
zip_command = "zip -qr '%s' %s" % (target, ''.join(source))
# Run Backup
if os.system(zip_command) == 0:
print "Succesful backup to", target
else:
print 'BACKUP FAILED :('
任何人都可以在Windows 7的命令行中为我提供一种方法吗?感谢您的时间,如果我未能提供相关信息,我会提前道歉:)
答案 0 :(得分:1)
对于python 3用户,使用format方法的答案应为:
# 1. The files and directories to be backed up are specified in a list.
source = [r'C\Users\MySourceDir']
# 2. The backup must be stored in a # main backup directory
target_dir = r'C:\Users\MyTargetDir'
# 3. The files are backed up into a zip file.
# 4. The name of the zip archive is the current date and time
target = target_dir + os.sep + time.strftime('%Y%m%d%H%M%S') + '.7z'
# Create target directory if it is not present
if not os.path.exists(target_dir):
os.mkdir(target_dir)
# 5. We use the zip command to put the files in a zip archive
zip_command = 'C:\\"Program Files"\\7-Zip\\7z a -t7z -r "{0}" "{1}"'.format(target,' '.join(source)) # be careful with spaces on each dir specification. Problems could arise if double-quotation marks aren't between them.
# Run the backup
print('Zip command is:')
print(zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
答案 1 :(得分:0)
zip
是用于创建/更新/提取ZIP存档的命令行实用程序,可在Unix / Linux / Mac OS X上使用。如果要使用命令行实用程序存档文件,则应找到并安装适当的on(compress
,例如,是资源工具包的一部分。)
另一种方法是使用python的zipfile
模块并为windows创建一个有用的命令行实用程序:)
答案 2 :(得分:0)
#!/usr/bin/python -tt
# Filename: backup_ver1.py
import os
import time
# 1. The files and directories to be backed up are specified in a list.
source = ['C:\\Documents\\working_projects\\', 'C:\\Documents\\hot_tips\\']
# 2. The back up must be stored in a main back directory
target_dir = 'C:\\temp\\backup\\'
# 3. The files are backed up into a zip file
# 4. The name of the zip archive is the current date and time
target = target_dir + time.strftime('%Y%m%d%H%M%S') + '.7z'
# 5. We use the zip command to put the files in a zip archive
#zip_command = "zip -qr '%s' %s" % (target, ' '.join(source))
zip_command = 'C:\\"Program Files"\\7-Zip\\7z a -t7z "%s" %s' % (target, ' '.join(source))
# Run the backup
if os.system(zip_command) == 0:
print 'Successful back up to', target
else:
print 'Backup FAILED'