如何替换字符串,其中两个单词由新行分隔?在Windows中创建的文件

时间:2014-01-28 15:38:13

标签: python newline

我试过了:

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,

“Macro.txt的案例1-20”如下所示:

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

1 个答案:

答案 0 :(得分:2)

不要遍历这些行,将所有内容作为字符串读取:

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