vieroli
vieroli

Reputation: 376

Search string and replace value

Here is my code,

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

The input_file :

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

I execute my script this way : modify_file.py NUM_COMM:nNN0.7 Hello world !

So if NUM_COMM:nNN0.7 exists in the file, it writes "NUM_COMM:nNN0.7" in a new axcfgpasww-modified.dat file.

But what I want to do, is execute my command as written above. And the result is the input file, with only the new value.

So my output file would be :

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

Can anyone help me on this ?

Thanks !

Upvotes: 1

Views: 83

Answers (1)

Radan
Radan

Reputation: 1650

I have made some refactoring to your original code, and made it produce the output you seek,

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)

output:

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

Hope this helps

Upvotes: 1

Related Questions