1. 程式人生 > 程式設計 >python按順序重新命名檔案並分類轉移到各個資料夾中的實現程式碼

python按順序重新命名檔案並分類轉移到各個資料夾中的實現程式碼

系統
ubuntu20.04
工具
python
要求
資料夾中有22個子資料夾,每個子檔案又包含56個檔案,要求將每個子資料夾中的第一個檔案放到一個新資料夾中,第二個放一個新的中,一直到最後。
解決方案
1.複製原始檔

import os
import shutil
#原始檔路徑
source_path='......'
#複製的新檔案的路徑
copy_source_path='.....'
#直接複製過去的話,經常會提示檔案存在,所以加個判斷語句
#判斷路徑是否存在原始檔,如果有則刪除
if os.path.exists(copy_source_path):
  shutil.rmtree(copy_source_path)
#複製檔案過去
shutil.copytree(source_path,copy_source_path)

保留原始檔可以增加自己操作的容錯性,並可以檢查自己操作是否滿足要求,當然也可以直接複製貼上原始檔

2.建立新資料夾

def creat(files):
#建立名稱為1~56的新資料夾
  for i in range(1,57):
 	#判斷路徑是否存在同名資料夾,如果沒有則建立
   if not os.path.exists(files +'/' +str(i)):
    os.makedirs(files +'/' +str(i))
#輸入路徑
creat('......')

3.按順序命名並轉移到新檔案中

#上面新資料夾所在路徑
target_path='.......'
#總資料夾路徑
for file in os.listdir(copy_source_path):
  j=1
  #拼接出檔案完整路徑
  source_path_1=os.path.join(copy_source_path,file)
  source_list=os.listdir(source_path_1)
  #對獲取的檔名排序,否則是亂序修改
  source_list_1=sorted(source_list)
  #子資料夾路徑
  for file_1 in source_list_1:
  #原始檔地址,這裡的原始檔我用的是複製的檔案
    oldname_path=os.path.join(source_path_1,file_1)
    #新資料夾路徑
    for file_2 in os.listdir(target_path):
      if str(j)==file_2:
        target_path_1=os.path.join(target_path,file_2)
        #新檔案路徑以及新名稱,這裡新名稱我是用的子檔名+檔案序號+檔案原來名稱,而上面的判斷語句就是判斷檔案序號與新資料夾名稱是否相同
        newname_path=os.path.join(target_path_1,file +'-'+str(j)+'-'+file_1)
        #renamen指令不僅能重新命名而且不保留原始檔以達到轉移的目的
        os.rename(oldname_path,newname_path)
    #要對每個子資料夾中的檔案順序命名,注意j所在的迴圈,不要放錯
    j+=1

到此這篇關於python按順序重新命名檔案並分類轉移到各個資料夾中的實現程式碼的文章就介紹到這了,更多相關python重新命名檔案並分類轉移到各個資料夾中內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!