BP_
BP_

Reputation: 2647

How to replace a string, where two words are separated by a new line? File created in Windows

I tried:

import fileinput

for line in fileinput.FileInput('Case 1-20 for Macro.txt', mode='U',inplace=1):
    line = line.replace("price_2\nFROM","zzzzz")
    print line,

"Case 1-20 for Macro.txt" looks like this:

SELECT type_id, name_id, scenario_id, period_id, date, price_1, price_2
FROM PricesView

Upvotes: 0

Views: 63

Answers (1)

zhangxaochen
zhangxaochen

Reputation: 34017

don't iterate over the lines, read all the contents as a string:

In [12]: with open(r'a.x') as f:
    ...:     content=f.read()
    ...:     print content
    ...:     content=content.replace("price_2\nFROM","zzzzz")
    ...:     print content
    ...:     
    ...: #if you want to write back that content:
    ...: with open('a.x', 'w') as f:
    ...:     f.write(content)
    ...:     

SELECT type_id, name_id, scenario_id, period_id, date, price_1, price_2
FROM PricesView
SELECT type_id, name_id, scenario_id, period_id, date, price_1, zzzzz PricesView

Upvotes: 2

Related Questions