【发布时间】:2020-06-07 03:40:14
【问题描述】:
如您所见,我正在尝试为自己创建一个小型备份脚本,以选择所需的文件并进行备份。
import shutil
import datetime
import os
import time
def backup():
# set the update interval
while True:
backup_interval = input("Please enter the backup interval in seconds: ") # 300
try:
valid_time = int(backup_interval) // 60
print("Backup time set to:", valid_time, "minutes!")
break
except ValueError:
print("This time is not valid, please enter a correct time in seconds: ")
print(">>> 60 seconds = 1 minute, 3600 seconds = 60 minutes.")
backup_file = input(r"Please enter the path for the file to backup: ") # D:\Python\BackupDB\test.db"
dest_dir = input(r"Please enter the destination path: ") # D:\Python\BackupDB\
folder_name = input(r"Please name your backup folder: ") # BD_Backup
now = str(datetime.datetime.now())[:19]
now = now.replace(":", "_")
# backup_file = backup_file.replace(backup_file, backup_file + str(now) + ".db")
# thats why I got the FileNotFoundError
final_destination = os.path.join(dest_dir, folder_name)
if not os.path.exists(final_destination):
os.makedirs(final_destination)
print("hello world")
shutil.copy(backup_file, final_destination)
第一个问题是,将文件复制到目标文件夹后如何替换名称以获得类似 test.db -> test_2020-02-23 08_36_22.db 喜欢这里:
source_dir = r"D:\Python\BackupDB\test.db"
destination_dir = r"D:\Python\BackupDB\BD_Backup\test_" + str(now) + ".db"
shutil.copy(source_dir, destination_dir)
输出:
test_2020-02-23 08_36_22.db
我在这里做错了什么? 以及如何将文件复制 5 次并在一段时间后 (backup_interval) 删除第一个并将最后 4 个向上移动并创建一个新文件,这样我总共拥有该文件的 5 个副本?
【问题讨论】:
标签: python-3.x database error-handling backup shutil