Python storing & accessing information via txt file

python storing data
python storing data in array
python storing data in text file
pickle python
python persistent data structures
storing python objects in a database
how to permanently store data in python
python storing data in memory

I'm writing a gambling/dice game program for a course I'm taking, each week new requirements are added, and we have to implement the new code w/o radically changing the code we have written thus far. The part I'm having trouble with is: right now, if the user quits (by entering "0" as their "bet"), the contents of their "bank" is saved to a text file, so they can resume play later with the same amount of "winnings". If the user goes bankrupt (game over), the next time they run the program their bank is reset to the default amount ($500). When the program starts, the code is supposed to check to see if a file holding previous play data (bank.txt) exists; if the file exists, the number in bank.txt is the user's "bank"; if the file doesn't exist, the program creates it and adds $500 to the user's bank. By tweaking things here and there I've gotten parts of the code to work (i.e., quit with $800 in bank, restart game and it's still there), but I've been at it so long (and am so frustrated) I just can't figure out what I'm doing wrong here.

> `import os
import random
def main():
    intro()
    bank = check_bank()
    show_bank(bank)
    bet = bet_validation(bank)`

That's the beginning of the program, obviously, the part I can't seem to get right is below... If I need to post more of the code, that's not a problem, it's just that everything else seems to work right (except for the following)

def check_bank():
    try:
        if os.path.isfile('./bank.txt') == True:
            bank_file = open('bank.txt','r')
            if float(bank_file.readline()) > 0.0:
                bank = float(bank_file.readline())
                return bank
            else:
                bank = 500.00
                return bank
        else:
            bank_file = open('bank.txt','w')
            bank_file.write(str(500.0))
            bank = float(bank_file.readline())
            bank_file.close()
            return bank
    except IOError:
        print('IOError in check_bank')
    except ValueError:
        print('ValueError in check_bank')
    except Exception as err:
        print(err,'in check_bank')
    finally:
        bank_file.close()

Any and all help/suggestions/tips would be greatly appreciated. When I start the program, I get a "ValueError" exception from the "check_bank()" function. I'd be happy to provide the rest of my code, if necessary, just included this bit because it seems to be where I'm having the problem. If you can help, please let me know what I'm doing wrong, and how to correct it! Thanks in advance guys!

Python Storing Data, Storing data to reuse it later is a central part in most Python applications. Whether you are doing a measurement in the lab or developing a web  Three Ways of Storing and Accessing Lots of Images in Python Setup. You will need an image dataset to experiment with, as well as a few Python packages. We will be using the Storing a Single Image. Now that you have a general overview of the methods, let’s dive straight in and look at a

Finally cracked it! Changed the following code around, and bingo!

def check_bank():
try:
    if os.path.isfile('./bank.txt') == True:
        bank_file = open('bank.txt','r')
        bank = float(bank_file.readline())
        if bank > 0:
            return bank
        else:
            bank = 500.0
            return bank

Python for the Lab Introduction to Storing Data in Files, For module-level code, there are only two namespaces to consider: the module global namespace and the built-in namespace that holds Python's essential  Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. However, Python does not have a character data type, a single character is simply a string with a length of 1. Square brackets can be used to access elements of the string.

You should not store your values in plain text. I prefer using pickle

import pickle, os

def check_bank():
    try:
        file_path = './bank.txt'

        #ckeck if file exists
        if os.path.isfile(file_path):
            file_handler = open(file_path,'rb')
            bank = pickle.load(file_handler)

            return bank

        #if the file doesn't exist    
        else:
            file_handler = open(file_path, 'wb')
            pickle.dump(500, file_handler)
            file_handler.close()
            return 500
    except IOError:
        print("IOError occured")

    except EOFError:
        #if the file is empty
        file_handler = open(file_path, 'wb')
        pickle.dump(500, file_handler)
        file_handler.close()
        return 500

Entering and Storing Data, Storing images on disk as .png files; Storing images in lightning memory-mapped databases (LMDB); Storing images in hierarchical data format (HDF5). You'll  Check out the docs for Python 2 or Python 3. Pickle isn't very robust though, and for more complex data you'll likely want to look into a database module like the built-in sqlite3 or a full-fledged object-relational mapping (ORM) like SQLAlchemy.

Three Ways of Storing and Accessing Lots of Images in Python , Storing data in JSON format. You might consider using JSON if your application needs to store somewhat complex data. While you may have  Slicing Lists in Python. We can slice lists as well. This gives us only a part of the list. Read slicing strings if you don’t remember. Slicing can take one, two or three values – start, stop and step.

Save and load Python data with JSON, Yes, we can use negative numbers as indices in Python. When we do so, the index -1 gives us the last element in the list, -2 the second to last, and so on. When you’re unpickling data, you’re essentially allowing your data source to execute arbitrary Python commands. If the data is trustworthy (say stored in a sufficiently protected directory), that may not be a problem, but it’s often really easy to accidentally leave a file unprotected (or read something from network).

Storing Multiple Values in Lists – Programming with Python, The Python list stores a collection of objects in an ordered sequence. sequence of any kind of Python object, the values stored in a dictionary – and with which  I am working on a project where I am storing DB and users's credentials inside python code. For example I have a script db.py which do crud operations and I am storing credential in this script as below- credentials = { 'UAT': { 'host': 'UAT_HOST

Comments
  • Can you replace except ValueError to except ValueError as e and then print(e)? Or just show a stack trace? Also you mixed up your else branch.
  • "Could not convert string to float"... The "string" in question is "500.0"
  • try to save that string into object and print it also to be sure that it doesn't contain wrong characters. Cause float('500.0') will work in 100% of cases.
  • Good job! You beat me to the answer by approximately 12 minutes! I was having a real hard time. There is code present to keep bank from dipping below 0 (game over once bank hits 0, input validation to keep player from betting more than they have in bank). I really, really appreciate that you took the time to help me out man!
  • Still being rather new, this answer is a bit beyond me... But I am intrigued. I will definitely be looking into what you've shown me here, and hopefully learn all I can from it.