somerandomguy95
somerandomguy95

Reputation: 161

Python3 - How to write a number to a file using a variable and sum it with the current number in the file

Suppose I have a file named test.txt and it currently has the number 6 inside of it. I want to use a variable such as x=4 then write to the file and add the two numbers together and save the result in the file.

    var1 = 4.0
    f=open(test.txt)
    balancedata = f.read()
    newbalance = float(balancedata) + float(var1)
    f.write(newbalance)
    print(newbalance)
    f.close()

Upvotes: 0

Views: 88

Answers (2)

Blckknght
Blckknght

Reputation: 104792

Files only read and write strings (or bytes for files opened in binary mode). You need to convert your float to a string before you can write it to your file.

Probably str(newbalance) is what you want, though you could customize how it appears using format if you want. For instance, you could round the number to two decimal places using format(newbalance, '.2f').

Also note that you can't write to a file opened only for reading, so you probably need to either use mode 'r+' (which allows both reading and writing) combined with a f.seek(0) call (and maybe f.truncate() if the length of the new numeric string might be shorter than the old length), or close the file and reopen it in 'w' mode (which will truncate the file for you).

Upvotes: 1

cdlane
cdlane

Reputation: 41905

It's probably simpler than you're trying to make it:

variable = 4.0

with open('test.txt') as input_handle:
    balance = float(input_handle.read()) + variable

with open('test.txt', 'w') as output_handle:
    print(balance, file=output_handle)

Make sure 'test.txt' exists before you run this code and has a number in it, e.g. 0.0 -- you can also modify the code to deal with creating the file in the first place if it's not already there.

Upvotes: 1

Related Questions