如何替换文本文件中的值?

时间:2019-07-16 17:38:55

标签: python file

我有一个名为test.py的设置文件。在此文件中,我必须替换一些floatintstring值。例如:ORDER_PAIRS = 0.01是一个float,我可以用另一个float值替换。并且ORDER_CONTENT = "some string"是一个string值。我需要读取这些值并用新值替换它们,然后覆盖文件。就像编辑设置文件一样。

示例:我需要将ORDER_PAIRS = 0.01更改为ORDER_PAIRS = 0.03或将ORDER_CONTENT = "some string"更改为ORDER_CONTENT = "some new string"

这是我的代码。

FileName = "test.py"

# Open file and replace line
with open(FileName) as f:
    updatedString = f.read().replace("ORDER_PAIRS = old value", "ORDER_PAIRS = " + new value)

# Write updated string to file
with open(FileName, "w") as f:
    f.write(updatedString)

如何更改某些值?

1 个答案:

答案 0 :(得分:0)

经过测试,并在Python 3.7.3上正常工作

import os
with open('newfile.txt','w') as outfile: #file to write, you can then rename your file
    with open('pytest.txt', 'r') as file: #contains your records
        a=file.read()
        if "ORDER_PAIRS = 11" in a:
            #print (a)
            b=a.replace('ORDER_PAIRS = 11','ORDER_PAIRS = 10')
            #print (b)
            outfile.write(b)
        else:
            outfile.write(a)
os.rename('pytest.txt','pytest.txt.bkp') # taking backup of old file
os.rename('newfile.txt','pytest.txt') #renaming new file back to old file