批量重命名文件

问题描述:

这是我的示例代码到一个文件夹,以连续的数字(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

假设输入文件名为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没问题!如果你喜欢它,你也可以赞不绝口! –