Shreya
Shreya

Reputation: 649

Read specific line and replace the data

I have a file1 as below

cell-(.Cd(),.cp(),.d(),.Q(n) );
Cmpe-(.A(),.B(),.s(n) );
And-(.A(),.A2(),.Z(n) );
Dff-(.Cp(),.D(),.Q(X) );

In this I want to read 2nd last line and replace its last () data with nb

The output is fout

cell-(.Cd(),.cp(),.d(),.Q(n) );
Cmpe-(.A(),.B(),.s(n) );
And-(.A(),.A2(),.Z(nb) );
Dff-(.Cp(),.D(),.Q(X) );

I tried the code below

f2=open('file1','r')
lines=f2.readlines()
last_lines = lines[-2:]
last_lines = last_lines.replace("n) );","nb) );")
f3=open('fout','w')
f3.write(last_lines)
f3.close()
f2.close()

The the code did not work getting error as list object has no attribute replace.

Upvotes: 0

Views: 56

Answers (1)

theWellHopeErr
theWellHopeErr

Reputation: 1872

You can take the line before the last line and replace it then write it, then write the last line separately.

f2=open('file1','r')
lines=f2.readlines()
line_before_last_line = lines[-2].replace("n) );","nb) );")      # replace line_before_last_line

f3=open('fout','w')
f3.writelines(lines[:-2])
f3.write(line_before_last_line)                                  # write line_before_last_line
f3.write(lines[-1])                                              # write last line
f3.close()
f2.close()

Upvotes: 2

Related Questions