简体   繁体   中英

How to extract number from a txt file

First my file

amtdec = open("amt.txt", "r+")
gc = open("gamecurrency.txt", "r+")

eg = gc.readline()
u = amtdec.readline()

The main code

user_balance = int(u)
egc = int(eg)

while True:
    deposit_amount = int(input("Enter deposit amount: $"))
    if deposit_amount<=user_balance:
            entamount = deposit_amount * EXCHANGE_RATE
            newgc = entamount + egc
            newamt = user_balance - deposit_amount

This is what my error was:

 user_balance = int(u)
ValueError: invalid literal for int() with base 10: ''

I was trying to compare a int in a file with my input.

Usually an error like this should turn you to check the formatting of your file. As some others mentioned, the first line could be empty for whatever reason. You can check for an empty file prior to this by doing the following:

test.txt contents: (empty file)

import os

f = open("test.txt")

if os.path.getsize("test.txt") == 0:
    print("Empty File")
    f.close()
else:
    print("Some content exists")

Output: "Empty File" (file is closed too since there is nothing to read)

Alternatively, you can read the entire file if you somehow can't access its contents (some schools do this). Using this technique will give you an idea of what you are dealing with in your file if you can't view it within your IDE:

f = open("test.txt")

for line in f:
    print(line)

f.close()

But let's say that just the first line of your file is empty. There are several ways you can check if a line is empty. If line 1 is blank but any line following it has content, reading line 1 from file will equal '\n':

test.txt contents: line 1 = '\n' (blank line), line 2 = 20.72

import os

f = open("test.txt")

if os.path.getsize("test.txt") == 0:
    print("Empty File")
    f.close()
else:
    print("Some content exists")

reader = f.readline()

# The second condition is if you are using binary mode
if reader == '\n' or reader == b"\r\n":
    print("Blank Line")

Output: "Some content exists" & "Blank line"

This is just my suggestion. As for your integer conversion, if you have a '.' in your currency amount, you will get a conversion error for trying to data cast it into an integer. However, I do not know if your currency will be rounded off to the nearest dollar or if you have any indication of change, so I will leave this to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM