0

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.

Shreya
  • 639
  • 4
  • 11
  • Because you are taking a list of the 2 last lines. But you only want one line, so why not just `lines[-2] = lines[-2].replace("n) );","nb) );")`? – Tomerikoo Nov 25 '20 at 14:33
  • Please read about [How to debug small programs](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). You can also use [Python-Tutor](http://www.pythontutor.com/visualize.html#mode=edit) which helps to visualize the execution of the code step-by-step. – Tomerikoo Nov 25 '20 at 14:34
  • ```lines[-2] = lines[-2].replace("n) );","nb) );")``` I get 2nd last line data getting replace. But how can I get this line replaced in my input file? – Shreya Nov 25 '20 at 14:40
  • Does this answer your question? [How to search and replace text in a file?](https://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file) – Tomerikoo Nov 25 '20 at 14:51
  • The question How to search and replace text in a file? In this specific text is being replace but I want to replace text in certain line number. – Shreya Nov 25 '20 at 14:57
  • Using ```f3.write(lines)``` is giving me ```error at f3.write(lines) as expected a character buffer object``` – Shreya Nov 25 '20 at 14:59
  • `f3.writelines(lines)`... – Tomerikoo Nov 25 '20 at 15:01

1 Answers1

2

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()
theWellHopeErr
  • 1,856
  • 7
  • 22