0

Suppose I have the following data in read.txt:

_app1_ip_
_app2_ip_
_app1_ip_
_app3_ip_
_app2_ip_

And I want to replace each with a certain corresponding value (in this case, the values in 'list') and output that to another file (out.txt):

list = ['app1', 'app2', 'app3']

for l in list:
   field = '_%s_ip_' %l

   patterns = {
      field : l,
   }

   with open("read.txt", "r") as my_input:
      content = my_input.read()
   with open("out.txt", "w+") as my_output:
      for i,j in patterns.iteritems():
         content = content.replace(i,j)
         my_output.write(content)

What I want is the following in data.txt:

app1
app2
app1
app3
app2

What I actually get is:

_app1_ip_
_app2_ip_
_app1_ip_
app3
_app2_ip_

This seems so simple.. would be an easy one-liner in bash/sed. Can anyone please help/explain?

1 Answer 1

1

After

list = ['app1', 'app2', 'app3']
for l in list:
    field = '_%s_ip_' %l
    patterns = {
        field : l,
    }

patterns only contains the last value, i.e.

patterns = {'_app3_ip_': 'app3'}

because you overwrite patterns in every loop iteration. Instead, you want to populate that dictionary. You can either do that with a for loop like you used:

list = ['app1', 'app2', 'app3']
patterns = {}
for l in list:
    field = '_%s_ip_' % l
    patterns[field] = l

or by using a dictionary comprehension:

patterns = {'_%s_ip_' % l: l for l in ['app1', 'app2', 'app3']}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the response. However, I'm getting: NameError: name 'patterns' is not defined when using patterns[field] = l. And it's not liking the syntax on the 2nd option (breaks at the for loop).
Okay fixed the first one... just needed to add patterns = {} at the top of the loop. It's now appending the replacements at the bottom of the file but leaving some untouched at the top... must be a problem with my replace code
Fixed. Just had to move (unindent) the write part to align with my for loop (i.e. only write once). Thanks valhallasw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.