-2

I have a settings file which is called test.py. In this file I have to replace some float, int, string values. eg: ORDER_PAIRS = 0.01 is a float that i can replace with another float value. And ORDER_CONTENT = "some string" is a string value. I need to read these values and replace them with new values, then overwrite the file. Like edit a settings file.

Example: I need to change ORDER_PAIRS = 0.01 to ORDER_PAIRS = 0.03 or ORDER_CONTENT = "some string" to ORDER_CONTENT = "some new string".

Here is my code.

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)

How can I change certain values?

Harshal Patil
  • 17,838
  • 14
  • 60
  • 126
mrdabanli
  • 33
  • 6
  • I want to replace the old value with new value, but i shouldnt hardcode the old value, it should read the old value and replace it with the new one. Like ORDER_PAIRS = x (the old value) should be replaced what i wanted. – mrdabanli Jul 16 '19 at 19:40
  • In that case, just _create_ the first string argument that's used in the call to `replace()` and put the desired old value you want in it (instead of hardcoding it). – martineau Jul 16 '19 at 20:29
  • The problem it is, how can i read the old value eg: ORDER_PAIRS = X the x value int or float sometimes.But other values can be string too, like ORDER_URL = "some string" i have to read all that different values and replace to the new. – mrdabanli Jul 16 '19 at 20:47
  • mrdabanli: That's also doable — just sounds like multiple replaces would need to be done. I suggest you [edit] your question again and try to describe what you want to do better and show your latest attempts at doing it. – martineau Jul 16 '19 at 20:55

1 Answers1

0

Tested and works fine on 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
ted
  • 13,596
  • 9
  • 65
  • 107
Karthik
  • 11
  • 5