批量重命名文件

2024-10-02 08:16:13 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是将文件夹中的文件重命名为连续数字(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”后面_解码.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

请给我举个例子。你知道吗


Tags: textimportosk2filesw1filedecoded
1条回答
网友
1楼 · 发布于 2024-10-02 08:16:13

假设输入文件名为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

相关问题 更多 >

    热门问题