2017-08-11 91 views
0

我試圖從一個目錄中取出一個文件名,例如'OP 40 856101.txt',刪除.txt,將每個單詞設置爲特定變量,然後重新排列文件名基於「856101 OP 040」等所需的順序。下面是我的代碼:一次在目錄中重命名多個文件

import os 


dir = 'C:/Users/brian/Documents/Moeller' 
orig = os.listdir(dir)     #original names of the files in the folder 

for orig_name in orig:    #This loop splits each file name into a list of stings containing each word 
    f = os.path.splitext(orig_name)[0] 
    sep = f.split()    #Separation is done by a space 
    for t in sep:   #Loops across each list of strings into an if statement that saves each part to a specific variable 
     #print(t) 
     if t.isalpha() and len(t) == 3: 
      wc = t 
     elif len(t) > 3 and len(t) < 6: 
      wc = t 
     elif t == 'OP': 
      op = t 
     elif len(t) >= 4: 
      pnum = t 
     else: 
      opnum = t 
      if len(opnum) == 2: 
       opnum = '0' + opnum 
    new_nam = '%s %s %s %s' % (pnum,op,opnum, wc)   #This is the variable that contain the text for the new name 

    print("The orig filename is %r, the new filename is %r" % (orig_name, new_nam)) 
    os.rename(orig_name, new_nam) 

但是我正在用我最後的for循環的錯誤,我嘗試重命名目錄中的每個文件。

FileNotFoundError: [WinError 2] The system cannot find the file specified: '150 856101 OP CLEAN.txt' -> '856101 OP 150 CLEAN' 

的代碼完全運行,直到os.rename()命令,如果我打印出變量new_nam,它打印出的所有目錄中的文件的正確的命名順序。似乎它找不到原始文件,儘管將文件名替換爲new_nam中的字符串。我認爲這是一個目錄問題,但是我對Python更新,似乎無法找到編輯我的代碼的位置。任何提示或建議將不勝感激!

回答

1

試試這個(只是改變最後一行):

 os.rename(os.path.join(dir,orig_name), os.path.join(dir,new_nam)) 

你需要告訴Python的文件的實際路徑重命名 - 否則,它看起來只有在包含該文件的目錄。

順便提一句,最好不要使用dir作爲變量名稱,因爲這是一個內置的名稱。

+0

工作!謝謝!! – Bkal05