260 likes | 564 Views
Exceptions, Pickles and Shelves. Storing Complex Data in Files. Text files store a series of characters What if you want to store lists or dictionaries in such a way that you could easily read them back in as lists or dictionaries? Python provides a way to do so, using the pickle module
E N D
Storing Complex Data in Files • Text files store a series of characters • What if you want to store lists or dictionaries in such a way that you could easily read them back in as lists or dictionaries? • Python provides a way to do so, using the pickle module • Of course, to use it you would have to import it:import pickle • We will demonstrate the use of the pickle module using an example # Pickle It # Demonstrates pickling data import pickle
print("Pickling lists.") variety = ["sweet", "hot", "dill"] shape = ["whole", "spear", "chip"] brand = ["Claussen", "Heinz", "Vlassic"] f = open("pickles1.dat", "wb") pickle.dump(variety, f) pickle.dump(shape, f) pickle.dump(brand, f) f.close() print("\nUnpickling lists.") f = open("pickles1.dat", "rb") variety = pickle.load(f) shape = pickle.load(f) brand = pickle.load(f) print(variety) print(shape) print(brand) f.close()
pickle methods • dump(object,file [,protocol]) • Writes pickled version of object to file • file must be an file object opened with mode wb • load(file) • Unpickles and returns the next pickled object in file • You can pickle a wide variety of Python objects • Numbers • Strings • Tuples • Lists • Dicitionaries • …
Shelves • A shelve is a pickled object accessed as if it were a dictionary. • It acts like a very simple, primitive database. • You connect a shelve object to a file by the shelve.open method. • There are four possible modes: • 'c' Open for reading or writing. If the file does not exist it is created • 'n' Create a new file for reading or writing. If the file exists, its contents are overwritten • 'r' Read from a file. If the file does not exists, Python will complain with an error • 'w' Write to a file. If the file does not exists, Python will complain with an error • When we execute myshelf = shelve.open('myfile.shv','c'), myshelf may now be used as if it were a dictionary. • However, any changes made to myshelf will not be written to the file until you execute myshelf.sync(), or you close the shelve using the command myshelf.close().
# Demonstrates shelving data import shelve print("\nShelving lists.") s = shelve.open("pickles2.dat") s["variety"] = ["sweet", "hot", "dill"] s["shape"] = ["whole", "spear", "chip"] s["brand"] = ["Claussen", "Heinz", "Vlassic"] s.sync() # make sure data is written print("\nRetrieving lists from a shelved file:") print("brand -", s["brand"]) print("shape -", s["shape"]) print("variety -", s["variety"]) s.close() input("\n\nPress the enter key to exit.")
Other Structured Data Systems • Pickling and unpickling are good ways to store and retrieve structured information • Especially Python objects • But more complex information can require even more power and complexity • Two popular, general methods are databases and XML. • Python has modules that can interface with each of the above. • In particular, the sqlite3 module provides an interface to relational databases, providing a rich set of SQL commands.
Exceptions • We have already seen how the Python interpreter reacts when an error occurs: • What has happened is that the interpreter has raised an exception, indicating that, well, something exceptional has occurred! • If nothing is done with the exception, Python halts what it is doing and prints an error message detailing the exception. • Note that the exception has a name: ValueError • In fact, the preceding is the name of an Exception type. • The next slide shows some common built-in Exception types • There are over two dozen separate built-in Exception types
Catching Exceptions: try:/except: • Instead of having the program halt when an exception occurs, one can surround the potential erroneous statement with try-except clause: try:num = float(input('Enter a number: ')) except: print("Something went wrong!") • It is much better to specify the expected error: try:num = float(input('Enter a number: ')) except ValueError: print("Something went wrong!")
Catching Multiple Exceptions • A single piece of code could result in more than one error (especially if it is part of a loop). • We can catch multiple errors: print() for value in (None, "Hi!"): try: print("Attempting to convert", value, "-->", end=" ") print(float(value)) except (TypeError, ValueError): print("Something went wrong!")
Catching Multiple Exceptions • Another way to catch multiple errors is by multiple except clauses: print() for value in (None, "Hi!"): try: print("Attempting to convert", value, "-->", end=" ") print(float(value)) except TypeError: print("I can only convert a string or a number!") except ValueError: print("I can only convert a string of digits!")
Using the Exception's Value • Each exception also generates a "value", a string describing the error from the interpreter's point of view: try: num = float(input("\nEnter a number: ")) except ValueError as e: print("That was not a number! Or as Python would say...") print(e)
Else Clause • You may also include and else clause that will be executed if there was no exception raised. try: num = float(input("\nEnter a number: ")) except ValueError: print("That was not a number!") else: print("You entered the number", num)
Extended Example: Trivia Challenge Game • The Trivia Challenge Game tests a player's knowledge with a series of multiple-choice questions. • The game delivers the questions as a single "episode." • Our episode is about the Mafia and is called "An Episode You Can't Refuse". • The questions are stored in a separate file independent of the game code. • Thus, anyone with a text editor can create their own trivia episode about whatever topic they choose. Here is our game in action
Extended Example: Trivia Challenge Game • The Trivia Challenge Game tests a player's knowledge with a series of multiple-choice questions. • The game delivers the questions as a single "episode." • Our episode is about the Mafia and is called "An Episode You Can't Refuse". • The questions are stored in a separate file independent of the game code. • Thus, anyone with a text editor can create their own trivia episode about whatever topic they choose. Here is our game in action The player is always presented with four inviting choices. But only one is correct.
Extended Example: Trivia Challenge Game • The first thing we must do is describe the layout of the information in the game file (its "format"). The first line is always our episode title. Generic Format <category> <question> <answer 1> <answer 2> <answer 3> <answer 4> <correct answer> <explanation> (There are more, but enough for now! See trivia.txt) Our game file contents An Episode You Cannot Refuse On the Run With a Mammal Let's say you turn state's evidence and need to "get on the lamb"/If you wait too long, what will happen? You'll end up on the sheep You'll end up on the cow You'll end up on the goat You'll end up on the emu 1 A lamb is just a young sheep
Extended Example: Trivia Challenge Game import sys def open_file(file_name, mode):"""Open a file.""" try: the_file = open(file_name, mode) except IOError as e: print("Unable to open the file", file_name, "Ending program.\n", e) input("\n\nPress the enter key to exit.")sys.exit() else: return the_file
Extended Example: Trivia Challenge Game def next_line(the_file): """Return next line from the trivia file, formatted.""" line = the_file.readline() line = line.replace("/", "\n") return line def welcome(title): """Welcome the player and get his/her name.""" print("\t\tWelcome to Trivia Challenge!\n") print("\t\t", title, "\n")
Extended Example: Trivia Challenge Game def next_block(the_file): """Return the next block of data from the trivia file.""" category = next_line(the_file) question = next_line(the_file) answers = [] for i in range(4): answers.append(next_line(the_file)) correct = next_line(the_file) if correct: # if correct != '' correct = correct[0] explanation = next_line(the_file) return category, question, answers, correct, explanation
Extended Example: Trivia Challenge Game def main(): trivia_file = open_file("trivia.txt", "r") title = next_line(trivia_file) welcome(title) score = 0 # get first block L = next_block(trivia_file) category, question, answers, correct, explanation = L
Extended Example: Trivia Challenge Game while category:# ask a question print(category) print(question) for i in range(4): print("\t", i + 1, "-", answers[i]) # get answer answer = input("What's your answer?: ") # check answer if answer == correct: print("\nRight!", end=" ") score += 1 else: print("\nWrong.",end=" ") print(explanation) print("Score:", score, "\n\n") # get next blockL = next_block(trivia_file) category, question, answers, correct, explanation = L
Extended Example: Trivia Challenge Game trivia_file.close() print("That was the last question!") print("You're final score is", score) # Executable part of the file main() input("\n\nPress the enter key to exit.")