gpt4 book ai didi

python - 搜索字符串并替换值

转载 作者:行者123 更新时间:2023-12-01 09:06:31 25 4
gpt4 key购买 nike

这是我的代码,

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')

输入文件:

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 !

有人可以帮我解决这个问题吗?

谢谢!

最佳答案

我对您的原始代码进行了一些重构,并使其产生您寻求的输出,

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!

希望这有帮助

关于python - 搜索字符串并替换值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52006648/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com