0

I am getting an odd problem. when I am trying to replace a string in a file. The relevant line in the file is:

 lattice parameter A  [a.u.] 
    5.771452243459

and I am trying to replace it as:

   with open(newsys, "r+") as finp:
        for line in finp:
            # print(line)
            if line.startswith("lattice parameter A  [a.u.]"):
                line = next(finp)
                print(line)
                print(Alat)
                line.replace(line.strip(), str(Alat))
                print(line)

the last 3 print statement gives:

    5.771452243459  # string that will be replaced

6.63717007997785    #value of Alat
    5.771452243459  #the line after replace statement

What is going wrong here?

1 Answer 1

1

replace method does not modify existing string. Instead it is creating a new one. So in line

line.replace(line.strip(), str(Alat))

You are creating a completely new string and discards it (because not assign to any variable).

I would do something like:

   with open(newsys, "r+") as finp:
        with open('newfile', 'w') as fout:
            for line in finp:
                # print(line)
                if line.startswith("lattice parameter A  [a.u.]"):
                    line = next(finp)
                    print(line)
                    print(Alat)
                    line = line.replace(line.strip(), str(Alat))
                    print(line)
                fout.write(line)
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.