【练习】检测U盘并自动复制内容到电脑的软件

软件作用:
    有U盘插在电脑上后,程序会检测到U盘的路径。
    自己可以提前设置一个保存复制文件的路径或者使用为默认保存的复制路径(默认为桌面,可自行修改)。
    检测到U盘后程序就会把U盘的文件复制到电脑对应的文件夹内。没有任何提示。
    目前应该还存在一些问题,但是简单的使用是可以满足。
    本机测试没多大问题。当然我的U盘有限,电脑有限,没经过充分的测试,不确保在其他电脑上可以正常运行。

除开功能,目前已知的问题:
  1、当在运行时关闭窗口会出现程序未响应会卡十几秒然后结束掉程序。
  2、默认保存路径不显示在界面上


后面会持续优化一下,并打包成exe文件,然后可以设置为开机自启动,这样就不用每次手动操作。

以下是源码:

import os
import shutil
import psutil
import tkinter
from tkinter import filedialog
 
#author==龙华
 
#主窗口创建
win=tkinter.Tk()
win.title('共享U盘')
win.geometry('300x200')
 
#桌面文件夹浏览,点击浏览可以在电脑上进行选择
def liulan_button():
    filename=filedialog.askdirectory()
    liulan.delete(0,tkinter.END)
    liulan.insert(0,filename)
 
#确定按钮执行动作,确定最终复制路径,启动复制函数
def qdbutton_click():
    fina_path=updata_path()
    copy_files_from_usb(fina_path)
 
#从U盘复制到自己电脑上
def copy_files_from_usb(fina_path):
    usb=get_usb_drive()
    for x in usb:
        usb_path = x
                # 遍历U盘中的文件和文件夹
        for foldername, subfolders, filenames in os.walk(usb_path):
            for filename in filenames:
                # 构建源文件路径和目标文件路径
                source_file = os.path.join(foldername, filename)
                destination_file = os.path.join(fina_path, filename)
                # 复制文件
                shutil.copy(source_file, destination_file)
                print(f"已复制文件:{filename}-{fina_path}")
 
        print("复制完成")
 
#获取u盘路径
def get_usb_drive():
    # 获取所有磁盘分区
    partitions = psutil.disk_partitions()
    li=[]
    # 遍历磁盘分区,查找U盘
    for partition in partitions:
        if 'removable' in partition.opts: #包含removable为U盘
            # 获取U盘路径
            usb_drive = partition.mountpoint[0:2]
            # s=usb_drive[0:2]
            li.append(usb_drive)
    return li
 
#确定最终的路径,如果不填路径则默认新建一个,如果浏览选择则使用新路径
def updata_path():
    new_path=liulan.get()
    if not new_path:
        new_path=moren_path
        if not os.path.exists(new_path):
            os.makedirs(moren_path)
    return new_path
 
#默认路径设置,默认放在桌面
moren_path=tkinter.StringVar()
moren_path.set(r'C:\Users\Administrator\Desktop\共享U盘文件')  #可修改默认路径
moren_path=moren_path.get()#获取默认路径
 
#创建浏览选择窗口
liulan=tkinter.Entry(win, textvariable=moren_path)
liulan.place(x=50,y=55)
 
#创建浏览按钮,绑定浏览函数
liulanButton=tkinter.Button(win,text='浏览',command=liulan_button)
liulanButton.place(x=200,y=50)
 
#创建确定按钮,绑定复制函数
quedingButton=tkinter.Button(win,text='确定',command=qdbutton_click,width=10,height=1)
quedingButton.place(x=80,y=100)
 
#author==longhua
 
# 测试 实例化
if __name__ == '__main__':
    win.mainloop()
    # copy_files_from_usb(quedingButton)

猜你喜欢

转载自blog.csdn.net/leavemyleave/article/details/134366248