首页 > 解决方案 > 从另一个文件替换字符串和文件

问题描述

我有两个文本文件, man.txt 和 job.txt

在 man.txt 我有

abc = "pqr"
abc1 = "xyz"

在 job.txt 我有

pqrst
xyz

我想在 Python 或 Unix中查找并替换"pqr"man.txt"pqrst"

我通过 abc 知道 pqr 是要替换的(abc 是特定的)

提前致谢

标签: pythonunix

解决方案


您可以使用fileinput.

import fileinput  

with fileinput.FileInput("man.txt", inplace=True) as file:
    for line in file:
        print(line.replace('abc = "pqr"', 'abc = "pqrst"'), end='')

推荐阅读