Hello everybody,

I wrote a script as like below

arr = [(line.rstrip('\n').split(';')) for line in open('C:/Config_Changer.csv')]
import sys
import fileinput
for i, line in enumerate(fileinput.input('C:/1.cfg', inplace = 1)):
    for f,t in arr:
        if 'description' not in line:
              line = line.replace(f, t)
    sys.stdout.write(line)

ok my problem is my config changer file is like
1/1/1;1/1/2
1/1/2:1/1/4

when I run the script it first change 1/1/1 to 1/1/2 then to 1/1/4 but I don't want that; I want that it changes 1/1/1 to 1/1/2 and 1/1/2 to 1/1/4 so when its replacing the values from array;I want that it should read from the first buffered file not the last changed file :) How can I do that ?

Thank you very much for all your help in advance

Recommended Answers

All 6 Replies

Member Avatar for Enalicho

Here's your problem -

for f,t in arr:
        if 'description' not in line:
              line = line.replace(f, t)

It will keep changing that line, for each value of f and t that you have in arr.
You need to break out of the for loop, or do something so that it only changes the line once.

yes I know but I can't break the loop.I need that it changes all the array.
What else can I do for changing a line once ?

Member Avatar for Enalicho

yes I know but I can't break the loop.I need that it changes all the array.
What else can I do for changing a line once ?

This doesn't make sense. Let's say you have a file with the line

1/1/1

And your arr values were [ (1/1/1, 1/1/2), (1/1/2, 1/1/3), (1/1/3, 1/1/4) ]

Going through the for loop -

Line -
1/1/1
Replace line, line is now 1/1/2
Replace line, line is now 1/1/3
Replace line, line is now 1/1/4


This isn't what you want, so if you had instead

Line -
1/1/1
Replace line, line is now 1/1/2, break

You wouldn't be having issues.

ok but afterwards
how can I change 1/1/2 to 1/1/3 if I break after changing 1/1/1 to 1/1/2 ?

Member Avatar for Enalicho

ok but afterwards
how can I change 1/1/2 to 1/1/3 if I break after changing 1/1/1 to 1/1/2 ?

For line in file:
    For f, t in arr:
        If line matches current value of f, replace and break

Nothing fancy, just try to think about what your for loops are doing.

I am not able to change loop correctly but with that break at least it's replacing one line correct :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.