如何在不使用python逐行搜索的情况下替换文件中的文本?

时间:2018-07-26 07:00:34

标签: python file replace

示例:

file1.txt包含1000行文本,无需逐行搜索,我需要替换它们

aaaa bbbbb cccc
asdfd raj ccc
ksdhfkj kjhkjh kjhkjh
raj

需要将 raj 替换为 shatish

aaaa bbbbb cccc
asdfd sathish ccc
ksdhfkj kjhkjh kjhkjh
sathish

是否可以替换而无需逐行搜索

1 个答案:

答案 0 :(得分:0)

也许:

with open("textfile","r") as fi, open("outfile","w") as fo:
    fo.write(fi.read().replace("raj","sathish"))