备份文件python代码
时间: 2023-11-20 15:55:57 浏览: 29
以下是一个备份文件的Python代码示例,它可以备份指定目录下的所有文件和子目录到指定的目标目录中:
```python
import os
import time
# 要备份的文件夹列表
source = ['/var/www/html/xxx1/', '/var/www/html/xxx2/']
# 备份目标文件夹
target_dir = '/backup/'
# 以当前日期作为子目录名
today = target_dir + time.strftime('%Y%m%d')
# 以当前时间作为压缩文件名
now = time.strftime('%H%M%S')
# 创建子目录
if not os.path.exists(today):
os.mkdir(today)
print('Successfully created directory', today)
# 备份文件的压缩文件名
target = today + os.sep + now + '.zip'
# 使用zip命令将文件备份到压缩文件中
zip_command = 'zip -r {0} {1}'.format(target, ' '.join(source))
# 运行备份命令
print('Zip command is:', zip_command)
print('Running:')
if os.system(zip_command) == 0:
print('Successful backup to', target)
else:
print('Backup FAILED')
```
该代码使用了Python的os和time模块,通过调用zip命令将指定目录下的所有文件和子目录备份到指定的目标目录中。你可以根据自己的需求修改源目录、目标目录和备份文件名等参数。