[英]How to replace values in text file?
我有一个名为 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)
如何更改某些值?
在 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.