lotus
lotus

Reputation: 111

Rename specific lines in a text file using python

    import re    
    rep_file = open('in2','r')
    new_words = []
    for line in rep_file:
        line = line.strip()
        new_words.append(line + '.ec3')

    infile = open('in.txt','r')    
    data = infile.read()    
    matches = re.findall(r'(opdut_decoded\.wav)',data)    
    i = 0    
    for m in matches:   

        data = re.sub(m,new_words[i],data,1)
        i += 1

    out = open('out.txt','w')  
    out.write(data)    
    out.close()

This is example code for rename a specific word("opdut_decoded") in a text file using another text file.This is working fine for me.But as i said in "Input File:" below I need to rename a same word(0a.ac3) in same line wherever the "opdut_decoded" is there.Can you please guide me for this.

New names in a text file:

0a

1b

2c

3d

I have a text file with these below lines

-c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -opdut_decoded.wav,opdut_decoded.wav,opdut_decoded.wav
-c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -opdut_decoded.wav,opdut_decoded.wav,opdut_decoded.wav
-c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -opdut_decoded.wav
-c0 -k2 -w1 -x1.0 -y1.0 -iLFE1.ac3 -opdut_decoded.wav

I want to replace given input lines above by"-opdut_decoded.wav" in every line like this

-c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -0a.ac3,0a.ac3,0a.ac3
-c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -1b.ac3,1b.ac3,1b.ac3
-c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -2c.ac3
-c0 -k2 -w1 -x1.0 -y1.0 -iLFE1.ac3 -3d.ac3

Upvotes: 2

Views: 742

Answers (1)

ppm9
ppm9

Reputation: 58

First half of your code is fine, but when you read the in.txt file you should be reading it line by line and then do the substitution.

import re

new_words = []

rep_file = open('in2.txt','r')

for line in rep_file:
    line = line.strip()
    new_words.append(line + '.ec3')

infile = open('in.txt','r')

i = 0
out = open('out.txt','w')

for inline in infile:
    inline = re.sub('opdut_decoded\.wav',new_words[i],inline)
    out.write(inline)
    i += 1

out.close()

with this you should be getting the output you require

-c0 -k2 -w1 -x1.0 -y1.0 -ia8.ac3 -0a.ec3,0a.ec3,0a.ec3

-c0 -k2 -w1 -x1.0 -y1.0 -ia9.ac3 -1b.ec3,1b.ec3,1b.ec3

-c0 -k2 -w1 -x1.0 -y1.0 -ia18.ac3 -2c.ec3

-c0 -k2 -w1 -x1.0 -y1.0 -iLFE1.ac3 -3d.ec3

Upvotes: 1

Related Questions