使用python定时复制同种命名格式文件

  1. 脚本介绍
    将数据库每天生成的数据库备份文件拷贝到指定网络文件夹
    (1)需要构造filename文件格式–同时获取当天的日期进行文件名替换
    (2)构造可视化操作界面
    (3)设置执行时间,每天执行一次。
    2.操作界面
    使用python定时复制同种命名格式文件_第1张图片

3.实现代码

import os
import shutil
import time
from datetime import datetime, timedelta, date
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
import schedule
import threading

def copy_files_to_network_share(source_dir, target_dir):
    today = date.today()
    today_str = today.strftime("%Y-%m-%d")

    for filename in os.listdir(source_dir):
        if filename.startswith("HNJC_" + today_str):
            source_file = os.path.join(source_dir, filename)
            target_file = os.path.join(target_dir, filename)
            shutil.copy(source_file, target_file)
            print(f"文件 {filename} 已成功复制到目标目录!")

def select_source_directory():
    global source_directory
    source_directory = filedialog.askdirectory()
    source_dir_label.config(text=source_directory)

def select_target_directory():
    global target_directory
    target_directory = filedialog.askdirectory()
    target_dir_label.config(text=target_directory)

def start_copy():
    if source_directory and target_directory:
        copy_files_to_network_share(source_directory, target_directory)
        status_label.config(text="复制完成!")
    else:
        status_label.config(text="请选择源目录和目标目录!")

def set_execution_time():
    global execution_time
    execution_time = time_combobox.get()
    schedule.clear()
    schedule.every().day.at(execution_time).do(start_copy)
    status_label.config(text="成功设置定时任务!")

def run_scheduled_job():
    def job_thread():
        while True:
            schedule.run_pending()
            time.sleep(1)

    # 创建并启动定时任务线程
    thread = threading.Thread(target=job_thread)
    thread.daemon = True
    thread.start()

# 创建主窗口
window = tk.Tk()
window.title("文件复制工具")

# 创建选择源目录按钮和标签
source_dir_button = tk.Button(window, text="选择源目录", command=select_source_directory)
source_dir_button.pack()
source_dir_label = tk.Label(window, text="请选择源目录")
source_dir_label.pack()

# 创建选择目标目录按钮和标签
target_dir_button = tk.Button(window, text="选择目标目录", command=select_target_directory)
target_dir_button.pack()
target_dir_label = tk.Label(window, text="请选择目标目录")
target_dir_label.pack()

# 创建执行时间选择框
time_combobox = ttk.Combobox(window, values=["00:00", "01:00", "02:00", "03:00", "04:00"])
time_combobox.current(0)
time_combobox.pack()

# 创建设置执行时间按钮
set_time_button = tk.Button(window, text="设置执行时间", command=set_execution_time)
set_time_button.pack()

# 创建开始复制按钮
copy_button = tk.Button(window, text="开始复制", command=start_copy)
copy_button.pack()

# 创建定时执行按钮
schedule_button = tk.Button(window, text="定时执行", command=run_scheduled_job)
schedule_button.pack()

# 创建状态标签
status_label = tk.Label(window, text="")
status_label.pack()

# 运行主循环
window.mainloop()

你可能感兴趣的:(python,python,数据库,开发语言)