【问题标题】:Scheduled task of copying files and directories with Python使用 Python 复制文件和目录的计划任务
【发布时间】:2015-10-17 21:57:05
【问题描述】:

我想编写一个脚本来复制一个目录的内容并将它们备份到另一个目录中。例如,我想将目录Bye 的内容备份到目录Cheese

我还希望脚本以这样一种方式工作,即每天在特定时间重复计划任务,例如晚上 8 点。现有文件夹应与正在复制的文件夹合并,新文件应替换现有文件夹。

【问题讨论】:

标签: python file replace copy copy-paste


【解决方案1】:

您需要一个事件调度程序。先安装schedule模块,即:

pip install schedule

这应该可以完成工作:

import os
import schedule
import shutil
import time

def job():
    source_folder = r'C:\Users\User\Desktop\Bye'    
    destination_folder = 'C:\Users\User\Desktop\Cheese'  

    for src_dir, dirs, files in os.walk(source_folder):
        dst_dir = src_dir.replace(source_folder, destination_folder, 1)
        if not os.path.exists(dst_dir):
            os.makedirs(dst_dir)
        for file_ in files:
            src_file = os.path.join(src_dir, file_)
            dst_file = os.path.join(dst_dir, file_)
            if os.path.exists(dst_file):
                os.remove(dst_file)
            shutil.copy(src_file, dst_dir)

schedule.every().day.at("20:00").do(job)

while 1:
    schedule.run_pending()
    time.sleep(1)

【讨论】:

    【解决方案2】:

    看看shutil库: https://docs.python.org/2/library/shutil.html

    例如

    >>> import shutil
    >>> shutil.copyfile('foo.txt', 'bar.txt')
    

    【讨论】:

    • 有数百个文件,我根据您在示例中给出的代码理解它说您需要命名所有文件。一件事是每天都会向服务器添加新文件,所以我需要一段代码: - 将文件夹的全部内容复制到系统上的不同服务器并用相同的文件替换所有文件名称 - 但也将代码设置为在一天中的特定时间运行
    • 您可能知道目录?如果是这样,列出目录并复制列表中的每个文件,或者复制目录。
    【解决方案3】:

    这很有趣。

    我建议你研究一下。我找到了一个可以按照您的要求工作的 Python 模块,它被称为 shutil (Docs),this 帖子解释了如何通过示例使用它。另外,还有几个相关的问题:How do I copy a file in python?How do I copy a file in python?Copy file or directory in Python。您有几个关于如何使用该模块的示例。

    你知道如何使用模块吗?文档只是为您提供模块功能的基础知识。如果您像我一样是编程新手,可能会感到困惑。但是我链接到类似问题的示例将为您提供很多指导!

    我知道您需要尽快解决它,但请进行一些研究并尝试解决它。一旦你有了一些基本的代码,就更容易为你提供帮助。

    干杯!!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-09-08
      • 1970-01-01
      • 2019-06-25
      • 2013-07-18
      • 1970-01-01
      • 2013-02-05
      • 2014-05-16
      相关资源
      最近更新 更多