2016-02-25 175 views
0

這是我的示例代碼到一個文件夾,以連續的數字(0,1,2,3 ...)中的文件重命名,並將其在文本文件中寫:批量重命名文件

import fnmatch 
import os 

files = os.listdir('.') 
text_file = open("out2.txt", "w")    
for i in range(len(files)): 
    if fnmatch.fnmatch(files[i], '*.ac3'): 
     print files[i] 
     os.rename(files[i], str(i) + '.ac3') 
     text_file.write(str(i) +'.ac3' +"\n") 

如果我有這些行的文本文件:在每一行這樣

1. -c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -opdut_decoded.wav 
2. -c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -opdut_decoded.wav 
3. -c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -opdut_decoded.wav 
4. -c0 -k2 -w1 -x1.0 -y1.0 -iLFE1.ac3 -opdut_decoded.wav 

我想「-opdut_decoded.wav」後寫入新的名稱:

1. -c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -opdut_decoded.wav 0.ac3 
2. -c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -opdut_decoded.wav 1.ac3 
3. -c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -opdut_decoded.wav 2.ac3 
4. -c0 -k2 -w1 -x1.0 -y1.0 -iLFE1.ac3 -opdut_decoded.wav 3.ac3 

認罪以一個例子來指導我。

+0

這是可能的嗎? – lotus

回答

1

假設輸入文件名爲out1.txt,輸出文件out2.txt,我相信下面的代碼將幫助你實現你想要什麼:

import os 

file1 = open("out1.txt", "r") 
file2 = open("out2.txt", "w") 

i = 0 
for file in os.listdir('.'): 
    if file.endswith('.ac3'): 
     print file 
     newname = str(i) + '.ac3' 
     os.rename(file, newname) 
     file2.write(file1.readline().rstrip() + ' ' + newname + '\n') 
     i += 1 
+0

謝謝你正在工作 – lotus

+1

@lotus沒問題!如果你喜歡它,你也可以讚不絕口! –