shutil.copy在os.makedirs之后失败

问题描述 投票:1回答:2

如您所见,我正在尝试为自己创建一个小的备份脚本,以选择所需的文件并备份它们。

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
2个回答
0
投票

之前我也遇到过类似的问题,原因是目录的创建在尝试访问目录之前尚未完成。复制之前简单的睡眠就可以确认这一点。


0
投票

我已根据需要修改了您的代码,

        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)

我喜欢,复制文件后,我将其重命名

© www.soinside.com 2019 - 2024. All rights reserved.