使用python替换文件中的字符串

时间:2016-08-11 13:13:19

标签: python-3.x

我遇到了一个奇怪的问题。当我试图替换文件中的字符串时。 文件中的相关行是:

 lattice parameter A  [a.u.] 
    5.771452243459

我试图将其替换为:

   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)

最后3个print语句给出:

    5.771452243459  # string that will be replaced

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

这里出了什么问题?

1 个答案:

答案 0 :(得分:1)

replace方法不会修改现有字符串。相反,它正在创建一个新的。所以在行

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

您正在创建一个全新的字符串并将其丢弃(因为没有分配给任何变量)。

我会做类似的事情:

   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)
相关问题