Exotic
Exotic

Reputation: 29

Subtracting Numbers From A .txt File In Python

I want to be able to open the file i have, and append it so that if i want to subtract the number in the file by 2, it would print out the answer in the console by opening the file and reading it.

e.g. if the number in the file was 156, i would have to subtract it by 2, which is 154, this will then be displayed on the console!

this is all i have so far:

a = file.open("xp.txt", "r")
a.read()
a.close()

How would i update it so that if i wanted to subtract it by an integer, that integer would be displayed on console?

Thanks in advance!

Upvotes: 1

Views: 765

Answers (2)

TheEagle
TheEagle

Reputation: 5992

Use readline instead of read so that you won't get an error when the file for example contains another empty line. Then, call strip on the result to eliminate possible whitespace. Finally, use int to convert the string to a number. Now you can do all the math you want with it:

with open("xp.txt", "r") as infile:
   value = infile.readline()

stripped = value.strip()
number = int(stripped)
newNumber = number - 2
print(newNumber)

Or shorter:

with open("xp.txt", "r") as infile:
   print(int(infile.readline().strip()) - 2)

To write the number to the same file, convert the number back to a string:

with open("xp.txt", "r") as infile:
   result = int(infile.readline().strip()) - 2

print(result)

with open("xp.txt" , "w") as outfile:
    outfile.write(str(result))

Upvotes: 1

Cory Kramer
Cory Kramer

Reputation: 117856

Assuming the file just contained that single value and nothing else, you could accomplish this using the following

with open('xp.txt', 'r') as f_in:
    value = int(a.read())
    value -= 2
    print(f'New value is {value}')

with open('xp.txt', 'w') as f_out:
    f_out.write(str(value))

Basically you open the file for reading, read the value into an integer, modify the value and display it, then re-open the file for writing to write the value back out.

Upvotes: 0

Related Questions