Reputation: 25
I want to replace a string in a Python code. Then, if x exists in an array, decrement the number in the next line, or remove the entire line if the number is zero.
My original file is:
good ${x}
hi 1
good ${y}
hi 2
good ${z}
hi 3
notgood ${t}
hi 1
The array:
p0 = [x, y, z]
And the python code:
r = open('replace.txt')
o = open('output.txt', 'w+')
for line in r:
for i in p0:
if i in line:
line = line.replace("good", "yes")
#line = line + 1
#line = line.replace("2", "1")
x = line
o.write(x)
r.close()
o.close()
When i put those 2 lines in a comment, it works. Otherwise, no. Can someone help me to improve this code?
with comments,
I get this result:
yes ${x}
hi 1
yes ${y}
hi 2
yes ${y}
hi 3
notgood ${t}
hi 1
What I expect (and my effort (without comments)):
yes ${x}
yes ${y}
hi 1
yes ${y}
hi 2
notgood ${t}
hi 1
I just want an little idea (not necessary the whole work). Thank you,
ADDED: In the input file, lines can be:
${x} = Set Variable 1000 // won't change
${x} = Set Variable B // won't change
${t} = Set Variable 1000 // won't change
${t} = Set Variable B // won't change
Upvotes: 0
Views: 178
Reputation: 3856
I think I got a bit carried away and ended up writing your code for you...
Please read How to create a Minimal, Complete, and Verifiable example next time before posting as this is considered unpolite otherwise...
def magic(line):
# returns the first number in that line
return [int(s) for s in line.split() if s.isdigit()][0]
p0 = ["x", "y", "z"]
# open the input file
with open('replace.txt') as f:
# read all lines as array
content = f.readlines()
# for all strings we are looking for
for i in p0:
# loop over all lines
j = 0
while j < len(content):
# if the current line contains the word we are looking for
if "${"+i+"}" in content[j]:
# replace "good" with "yes"
content[j] = content[j].replace("good", "yes")
# somehow find the number we want to decrement in the next line
magic_number = magic(content[j+1])-1
if magic_number == 0:
# delete the next line
del content[j+1]
else:
# decrement the number
content[j+1] = content[j+1].replace(str(magic(content[j+1])), str(magic_number))
# skip the second line
j += 1
# go to next line
j += 1
with open('output.txt', "w+") as o:
o.writelines(content)
This creates an output file that look like this:
yes ${x}
yes ${y}
hi 1
yes ${z}
hi 2
notgood ${t}
hi 1
Upvotes: 1