0

I am currently using a list ['/etc/hostname', '/opt/sme/sme.conf'] in python script, and to do find and replace oldhostname with newhostname in those files in the list, which works great.

filelist = ['/etc/hostname', '/opt/sme/sme.conf']  
for filename in filelist :  
    f = open(filename,'r')
    filedata = f.read()
    f.close()

    newdata = filedata.replace('oldhostname',newhostname)

    f = open(filename,'w')
    f.write(newdata)
    f.close()

now I have to replace environment value in a file. Instead of repeating above code twice to replace environment value in a file. Can someone please suggest how to write above code using a tuple as input. [('newhostname',oldhostname,'/etc/hostname'),('newhostname',oldhostname,'/opt/sme/sme.conf'),('appenv',newappEnv,'/opt/sme/sme.conf')]

1 Answer 1

1

What you are looking for is called tuple unpacking

new_configurations = [('newhostname',oldhostname,'/etc/hostname'),('newhostname',oldhostname,'/opt/sme/sme.conf'),('appenv',newappEnv,'/opt/sme/sme.conf')]

for newhostname, oldhostname, filename in new_configurations : 
    f = open(filename,'r')
    filedata = f.read()
    f.close()

    newdata = filedata.replace(oldhostname,newhostname)

    f = open(filename,'w')
    f.write(newdata)
    f.close()
Sign up to request clarification or add additional context in comments.

Comments

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.