搜索字符串并替换值

时间:2018-08-24 14:30:00

标签: python regex

这是我的代码,

import os, os.path
import collections
import sys
import re

DIR_DAT = "dat"
DIR_OUTPUT = "output"
filenames = []
data = []

#in case if output folder doesn't exist
if not os.path.exists(DIR_OUTPUT):
    os.makedirs(DIR_OUTPUT)

input_file = 'axcfgpasww-from-server.dat'
element = sys.argv[1]
output_value = sys.argv[2]

with open(input_file) as infile, open('axcfgpasww-modified.dat', "w") as outfile:
    if element in open(input_file).read():
        regex = re.findall("\s*([\S\s]+)", element)

        outfile.write(regex[0])
        print(regex[0])
    else:
        print('No match found')

input_file:

CMD_VERS=2
CMD_TRNS=O
CMD_REINIT=N
CMD_ORDER=MAJECR
CMD_COMM=2590552
NUM_COMM:nNN0.7=2590552

我以这种方式执行脚本:modify_file.py NUM_COMM:nNN0.7 Hello world !

因此,如果文件中存在NUM_COMM:nNN0.7,它将在新的axcfgpasww-modified.dat文件中写入“ NUM_COMM:nNN0.7”。

但是我想做的是执行上面写的命令。结果是输入文件,只有新值。

所以我的输出文件将是:

CMD_VERS=2
CMD_TRNS=O
CMD_REINIT=N
CMD_ORDER=MAJECR
CMD_COMM=2590552
NUM_COMM:nNN0.7=Hello world !

有人可以帮我吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

我已经对您的原始代码进行了一些重构,并使其产生您想要的输出,

import os, os.path
import collections
import sys
import re

DIR_DAT = "dat"
DIR_OUTPUT = "output"
filenames = []
data = []
found = False

#in case if output folder doesn't exist
if not os.path.exists(DIR_OUTPUT):
    os.makedirs(DIR_OUTPUT)

input_file = 'axcfgpasww-from-server.dat'
element = sys.argv[1]
output_value = sys.argv[2]

with open(input_file) as infile:
    for line in infile.readlines():
        if element in line:
            old_value = line.split("=")[1]
            data.append(line.replace(old_value, output_value))
            found = True
        else:
            data.append(line)
if not found:
    print('No match found')

with open(input_file, 'w') as outfile:
    for line in data:
        outfile.write(line)

输出:

CMD_VERS=2
CMD_TRNS=O
CMD_REINIT=N
CMD_ORDER=MAJECR
CMD_COMM=2590552
NUM_COMM:nNN0.7=Hello World!

希望这会有所帮助

相关问题