3

I have a problem, but I can't figure out where it is going wrong.

What I am getting from this is that there is a empty thing or a space but there definitively isn't any in my text file. The goal of my code is to add money to a text file separated by a comma and turn that into an integer list.

Bonus: If you know anything about Pycharm how do you get rid of the '>?' when typing in an input.

My error:

File "C:/Users/hayde/PycharmProjects/Finance/Money.py", line 32, in <listcomp>
    int_tot = [int(i) for i in str_tot]
ValueError: invalid literal for int() with base 10: ''

My code:

def add_money():
    money = str(input("Amount: "))   
    #if '' in money: #if i run this it loops forever
        #return add_money()
    with open(r"C:\Users\hayde\OneDrive\Desktop\account.txt", 'a') as account:  
        account.write(',' + money)                    
    with open(r"C:\Users\hayde\OneDrive\Desktop\account.txt", 'r') as account:  
        if account.read(1) == ',':                                 
            print("Please clear account file, then have 0 be the only value in file")
            return                  
        for cash in account:
            str_tot = cash.split(',')  
    int_tot = [int(i) for i in str_tot]
    return int_tot
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 4
    Does this answer your question? [ValueError: invalid literal for int() with base 10: ''](https://stackoverflow.com/questions/1841565/valueerror-invalid-literal-for-int-with-base-10) – Surya Shekhar Chakraborty Jun 29 '20 at 04:05
  • 1
    In the list comprehension please try adding a if condition as follows `int_tot = [ int(i) for i in str_tot if i != ""`. – Kashyap KN Jun 29 '20 at 04:07
  • I tried that earlier by adding int(float(_)) but to no avail, maybe I am just not understanding it completely. (answering Surya ill try Kashyap KN solution right now) – jfwinston32 Jun 29 '20 at 04:10
  • 1
    `''` is the empty string. in `str_tot = cash.split(',')`, one of those fields is empty. You could read the file to see if there are any back-to-back commas or a comma at the end. When an amount is entered, you don't check whether the user just hits return, giving your an empty string. In that case, you'd end up with an empty field in the file. – tdelaney Jun 29 '20 at 04:10
  • 1
    Try this. int_tot = `[int(strip(i)) for i in str_tot if i != ""]` – MOHAMMED NUMAN Jun 29 '20 at 04:12
  • So I tried the conditional statement and everything ran smoothly. I am so thankful for all of your guys's timely responses, it is much appreciated!! But I didnt understand why it worked but I think tdelaney covered that up but I am not sure what "one of those fields" means. EDIT: this is my exact copy paste from txt file: >>0,70,80,90,90 – jfwinston32 Jun 29 '20 at 04:14
  • **Please provide a [mcve].** What do you understand from that error message? Have you done any debugging? – AMC Jun 29 '20 at 04:28

4 Answers4

4

One reason for getting that error is when you call int() on a string that is empty:

int_tot = [int(i) for i in str_tot]

You can use a filter to only convert and keep non-empty strings:

int_tot = [int(i) for i in str_tot if i]

if i in this case, means if i != ''.

Red
  • 26,798
  • 7
  • 36
  • 58
1

When you split the line by a comma, if the first character in that line is a comma, the first value in the list is ''. So, that is why the error arises.

To fix this, don't add a comma to a new line or don't add a comma as the first character of a line.
Or you can simply remove the '' from the list by .remove(0).

Red
  • 26,798
  • 7
  • 36
  • 58
JaysFTW
  • 101
  • 6
1

The problem seems to be that on str_tot one or more elements can not be converted to int that is why you are getting a ValueError. Please check the file to verify that you don't have strings or blank spaces, you could also add an exception handling as follow:

str_tot = [1, 2, 3, '3rjr', 6, 7]
int_tot = []

for i in str_tot:
    try:
        int_tot.append(int(i))
    except ValueError:
        print('Error, value: ', i)
print(int_tot)

Output:

Error, value:  3rjr
[1, 2, 3, 6, 7]
Mateo Lara
  • 827
  • 2
  • 12
  • 29
1

There are a few things I ran into running your code. It was really hard for me to actual create a file without a trailing newline, which would be considered a space.

I was able to create such a file with echo -n '0' > account.txt, this will delete your text file and replace it with just a 0.

Second, is that once you call account.read(1) you actually move the file pointer forward so that account is now offset by 1 character. Then when you try to iterate the file pointer is off by one, always starting at a comma because 0 is the start of the file. So if you call account.seek(0) before splitting it should work.

def add_money():
    money = str(input("Amount: "))   
    #if '' in money: #if i run this it loops forever
        #return add_money()
    with open(r"C:\Users\hayde\OneDrive\Desktop\account.txt", 'a') as account:  
        account.write(',' + money)                    
    with open(r"C:\Users\hayde\OneDrive\Desktop\account.txt", 'r') as account:
        if account.read(1) == ',':                                 
            print("Please clear account file, then have 0 be the only value in file")
            return
        # Return to the beginning of the file after reading 1 character.
        account.seek(0)
        
        for cash in account:
            str_tot = cash.split(',')  
    int_tot = [int(i) for i in str_tot]
    return int_tot
Ian Wilson
  • 6,223
  • 1
  • 16
  • 24