这是我的示例代码,用于将文件夹中的文件重命名为连续的数字(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
请举一个例子指导我。
假设输入文件名为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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句