WaXxX333
WaXxX333

Reputation: 486

Best way to append a float in a file with python?

I have a file with several variables that looks like this:

BTC = 375.23
SOL = 200.42
LTC = 208.91
DOT = 60.12

And a main script. How can I append those values ? Example: change BTC = 375.23 to BTC = 420.32. The methods I'm using are:

from varfile import * # imported this way for trial and error
from varfile import BTC # imported this way for trial and error
import varfile

def blah():
    varfile.BTC.append(float(420.32))
blah()

But I'm getting an error: AttributeError: 'float' object has no attribute 'append' I feel like I just need to convert the float to str somehow but not having luck. I've found a couple similar posts but nothing quite the same and nothing that works the way I'd like.

Let me clarify a little and maybe add some context. There is 2 files, one is my main script and the other file contains data - the variables I mentioned that are in varfile.py. The data file doesn't need to be any specific type of file, it can be a txt file or json, anything. When the main script is ran, I want it to read the values to the variables BTC, SOL and so on. After those values are read and used in the function, I want to change those values for next time I run the main script.

Upvotes: 0

Views: 450

Answers (1)

Alexander
Alexander

Reputation: 17311

The reason you are getting the error is because varfile.BTC is a float.

import varfile

def blah():
    # varfile.BTC = 345.23 which is a float and has no append method
    varfile.BTC.append(float(420.32))  
blah()

If your goal is to simply change the value of the variable at runtime, This will suffice.

varfile.BTC = 0.1     # or some other value

If your goal is to change the actual contents of the file, then it shouldn't be saved in a .py file, and shouldn't be imported into your script.

If you you wanted to change the value in a plain text file it would look something like this.

BTC = 10 # this is the value you want to change it to
varfile = 'varfile.txt'

with open(varfile, 'rt') as txtfile:
    contents = txtfile.read().split('\n')
    #  contents.append("BTC = " + str(BTC))   # this line is if you just wanted to add a value to the end of the file.
    for i,line in enumerate(contents):
        if 'BTC' in line:
            contents[i] = 'BTC = ' + str(BTC)
            break

with open(varfile, "wt") as wfile:
    wfile.write('\n'.join(contents))

Upvotes: 3

Related Questions