搜索并替换文档中的行

时间:2017-10-14 15:08:16

标签: python

我正在尝试编写一个代码,用于搜索和替换文档中的一行。我有:

import re
x = open(r'F:\1\xxx.txt')
string = open(r'F:\1\xxx.txt').read()
Lines = x.readlines()
new_str = re.sub('zzz1', (Lines[1]) , string)
new_str = re.sub('zzz2', (Lines[2]) , string)

open(r'F:\1\xxx2.txt', 'w').write(new_str)

在xxx1文档中,我已经为测试而写了

1
2
3
4
5
6
7
8
9
10
zzz1
zzz2

但是我在xxx2文档中得到的输出是

1
2
3
4
5
6
7
8
9
10
zzz1
3

知道我做错了什么?

1 个答案:

答案 0 :(得分:0)

工作解决方案:

导入重新 x =打开(r' F:\ 1 \ xxx.txt') Lines = x.readlines()

repldict = {' zzz1' :( Lines [0])。strip(),' zzz2' :( Lines [1])。strip()} def replfunc(匹配):     return repldict [match.group(0)]

regex = re.compile(' |' .join(re.escape(x)for x in repldict)) 打开(r' F:\ 1 \ xxx.txt')作为fin,打开(r' F:\ 1 \ xxx2.txt'' w')as f输出:     对于线路:         fout.write(regex.sub(replfunc,线))

相关问题