Search code examples
pythonfilevariablespython-3.x

how to update a variable in a text file


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


Solution

  • 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