如您所见,我正在尝试为自己创建一个小的备份脚本,以选择所需的文件并备份它们。
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个副本?
最佳答案
我已根据需要修改了您的代码,
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
old_file_name=backup_file.split("/")[-1]
now = str(datetime.datetime.now())[:19]
now = now.replace(":", "_")
new_file_name = old_file_name.split(".")[0]+"_" + str(now) + ".db"
final_destination = os.path.join(dest_dir, folder_name)
if not os.path.exists(final_destination):
os.mkdir(final_destination)
new_file="/"+new_file_name
shutil.copy(backup_file, final_destination)
os.rename(final_destination+'/'+old_file_name,final_destination+new_file)
我确实喜欢,复制文件后,我只是将其重命名
关于python-3.x - os.makedirs之后shutdownil.copy失败,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60360158/