how to update a variable in a text file

Question:

I have a program that opens an account and there are several lines but i want it to update this one line credits = 0 Whenever a purchase is made I want it to add one more to the amount this is what the file looks like

['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']

credits = 0

this bit of info is kept inside of a text file I don’t care if you replace it (as long as it has 1 more) or whether you just update it. Please help me out 🙂 sorry if this question is trival

Asked By: Marcello B.

||

Answers:

You can create a general text file replacer based on a dictionary containing what to look for as keys and as corresponding values what to replace:

In the template text file put some flags where you want variables:

['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']

credits = <credit_var>

Then create a mapping dictionary:

map_dict = {'<namef>':'New name', '<credit_var>':1}

Then rewrite the text file doing the replacements:

newfile = open('new_file.txt', 'w')
for l in open('template.txt'):
    for k,v in map_dict.iteritems():
        l = l.replace(k,str(v))
    newfile.write(l)
newfile.close()
Answered By: Saullo G. P. Castro

The below code snippet should give you an idea on how to go about. This code updates, the value of the counter variable present within a file counter_file.txt

import os

counter_file = open(r'./counter_file.txt', 'r+')
content_lines = []

for line in counter_file:
        if 'counter=' in line:
                line_components = line.split('=')
                int_value = int(line_components[1]) + 1
                line_components[1] = str(int_value)
                updated_line= "=".join(line_components)
                content_lines.append(updated_line)
        else:
                content_lines.append(line)

counter_file.seek(0)
counter_file.truncate()
counter_file.writelines(content_lines)
counter_file.close()

Hopefully, this sheds some light on how to go about with solving your problem

Answered By: Prahalad Deshpande

Rather than creating new files like new_file.txt or template.txt, you can use your existing file. Here I am using client_name and client_credit_score as place holders reflecting user data:

client_name="Joseph"
client_credit_score=1

map_dict = {'<namef>':f'{client_name}', '<credit_var>':f'{client_credit_score}'}
template = """['<namef>', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']    
credits = <credit_var>"""

with open('existing_file.txt', 'w') as f:
    for k,v in map_dict.items():
      template = template.replace(k,str(v))
    f.write(template)

Here the existing_file.txt will have this code initially (like you question):

['namef', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 0

And thanks to the map_dict, all the keys will be updated with new values in your file. Here’s what output will look like:

['Joseph', 'namel', 'email', 'adress', 'city', 'state', 'zip', 'phone', 'phone 2']
credits = 1

Note: Special thanks to @Saullo and @Tarun for the above answer.

Answered By: Muhammad Ali
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.