0

Unnecessary Context: I'm playing around with trying to make a discord bot (using discord.py) for me and my friends. Currently I'm trying to implement a shop and currency system, I have everything worked out except for converting the .txt contents to an integer

Question: How do I convert the contents of a text file to an integer? Relevant code below:

r = open("money.txt", "r")
money = r.read
x = money # int of text in file somehow
r.close()
w = open("money.txt", "w")
w.write(x)
w.close()
print(x)

Edit: I apologize, I should've said that I tried to int(money) and it gave an error saying: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method.' I fixed the problem by adding parentheses to the money variable so it was money = r.read()

  • 5
    What research have you done before posting here in accordance with [ask]? Casting string variables to integers is not only a fundamental tenet of the Python language, it's a duplicate of [Converting String to Int using try/except in Python](https://stackoverflow.com/questions/8075877/converting-string-to-int-using-try-except-in-python) (probably among quite a few others here). – esqew Feb 20 '22 at 23:06
  • 1
    Tangential: `read()` is a method - you won't get very far if you don't *call* it in line 2 of your snippet. – esqew Feb 20 '22 at 23:07
  • I apologize, I should've said that I tried to int(money) and it gave an error saying: int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' | I fixed the problem by adding parentheses to the money variable so it was money = r.read() – Kenma_Saiki Feb 21 '22 at 02:47

1 Answers1

2

Use int() to convert a str to an int:

with open("money.txt", "r") as r:
    money = r.read()    # money is raw text from the file

x = int(money.strip())  # x is money as an int

with open("money.txt", "w") as w:
    w.write(str(x))

print(x)

Note that you need to call r.read by saying r.read(), and you probably want to strip() the string before converting it to int, since it's likely to have a linebreak at the end.

You can avoid having to close() the file by using the with syntax, which automatically closes it as soon as the block ends.

Samwise
  • 68,105
  • 3
  • 30
  • 44
  • Consider adding some error handling – M. Villanueva Feb 21 '22 at 00:47
  • 1
    The only kind of error handling you could really add here would be to swallow the potential `ValueError`, which would just be detrimental to debugging efforts if that situation did come up. – Samwise Feb 21 '22 at 00:52
  • ... or a `FileNotFoundError` if the file does not exist, or a `MemoryError` if the file size is bigger than available RAM or a `PermissionError` if the current user is not allowed to open the file in read mode. A lot can go wrong. But I agree that these errors should be handled somewhere else in the code. – Richard Neumann Feb 21 '22 at 01:45