I have a code for a game.

money_file = open ('money.$','r').read()
money_file = str(money_file)
money = int(money_file)

But everytime I run it, it returns an error:

Traceback (most recent call last):
  File "C:\Users\eeo.j\Desktop\CX6 SDK\CX6 Normal\CX6.py", line 86, in <module>
    money = int(money_file)
ValueError: invalid literal for int() with base 10: ''

I need to get the money variable into an interger, but I can't.
Anyone got any idea what's going on?

The error message is telling you that you're trying to convert an empty string into a number. So are you sure that your 'money.$' file isn't empty?

The error message is telling you that you're trying to convert an empty string into a number. So are you sure that your 'money.$' file isn't empty?

I entered values into the 'money.$' file and it works perfectly now. Thanks!
BTW is there any way that you could turn an empty string into a number?

You could check whether the string is empty and in that case just return 0 (or whatever number you want the empty string to represent).

You could check whether the string is empty and in that case just return 0 (or whatever number you want the empty string to represent).

@sepp2k: How do I do it? Can you provide me with an example?

You could add a few test prints:

# write a test file
data = '177'
with open('money.$','w') as fout:
    fout.write(data)

# read file back in
money_file = open('money.$','r').read()
# test print value and type
print money_file, type(money_file)

'''result >>
177 <type 'str'>
'''

if money_file:
    money = int(money_file)
    print money

If you need several integer values in your file, do this:

# write a test file using several integers
data = """\
177
233
567
876
"""
with open('money.$','w') as fout:
    fout.write(data)

# now read the test file back in as a list
money_list = []
for line in open('money.$','r'):
    # strip whitespaces and convert string to integer
    money = int(line.strip())
    money_list.append(money)

# test
print money_list     # [177, 233, 567, 876]
print money_list[1]  # 233
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.