大家好
突然想到如何用 python 寫一個程式把資料夾所有檔案搬移到另一個資料夾,並且平均分配?
並且遇到重複檔案名稱會重新加上隨機數字做後綴避免重複
主要是有些檔案真的很多
但是又需要保留
但是都放在一個資料夾非常大
難以打開
所以如果可以平均放在資料夾中並且設定一個數量去填滿
啟不美哉?
import os import shutil import random source_directory = r'C:/Users/MYDIR/Downloads/TMP/FROM/' put_directory = r'C:/Users/MYDIR/Downloads/TMP/PUT/' files_per_folder = 10 #每個資料匣最多放幾個 preType = 'C' folder_counter = 0 file_counter = 0 nowDirCount = 1 # 遍歷源資料夾及其子資料夾中的檔案 for root, dirs, files in os.walk(source_directory): for file in files: orgPath = root + '/' + file while True: nowDirF = preType+('000'+str(nowDirCount))[-3:] nowDirP = put_directory + nowDirF # 檢查是否需要創建新的子資料夾 if not os.path.exists(nowDirP): os.makedirs(nowDirP) existing_file_counts = len(os.listdir(nowDirP)) # 目前資料夾檔案超過數量,下一個 if existing_file_counts >= files_per_folder: nowDirCount += 1 continue newPath = nowDirP + '/' + file # 如果資料夾中有同名檔案則改檔案名稱 if os.path.exists(newPath): newPath = nowDirP + '/' + file[:-4] + '_' + str(random.randint(1000, 9999)) + file[-4:] # 下一步 break print("MOVE = ", orgPath, ' TO ', newPath) shutil.move(orgPath, newPath)
出來的資料夾還可以自訂前面一個單字好分類
大概像這樣
原本是想用 chat gpt 幫我寫這一段程式碼
發現 gpt 很難理解我要的意思
所以還是自己寫比較快
而且發現GPT對於複雜問題的理解能力還是不夠好
而且GPT無法判斷他自己是否真的理解描述
只能硬吐答案
如果是人
遇到聽不懂的描述
會問 "哈?"
但是GPT確實還無法思考
他沒有自我
沒辦法跟自己對話說
自己是否真的理解對方的意思
不過如果真的可以的話
那也是相當可怕的事情
留言板
歡迎留下建議與分享!希望一起交流!感恩!