我有一个名为test.py的设置文件。在此文件中,我必须替换一些float
,int
,string
值。例如: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)
如何更改某些值?
答案 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