Search code examples
pythonpython-2.7filerenamebatch-rename

Batch renaming files


This is my example code to rename the files in a folder to consecutive numbers (0, 1, 2, 3 ....) and write them in a text file:

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")

If I have a text file with these lines:

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

I want to write the new name after "-opdut_decoded.wav" in every line like this:

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

Please guide me for this with an example.


Solution

  • Assuming the input file is named out1.txt, and the output file as out2.txt, I believe the following the code would help you achieve what you want:

    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