Binary Files
Overview Text file are convenient because you can read and change them using any text editor However, text files are limited to only text characters Sometimes you need to store more complex data structures Binary files allow you to store list and dictionary data structures You can’t change binary files with a text editor
Pickle In Python, pickling is a means to preserve complex data You can write lists or dictionaries For pickled data, you must read in the same order written You must ‘import pickle’ to gain access to the pickle code
Selected Binary File Access Modes “rb” Read from a binary file. If the file doesn’t exist, Python will complain with an error “wb” Write to a binary file. If the file exists, its contents are overwritten. If the file doesn’t exist, it’s created “ab” Append a binary file. If the file exists, new data is appended to it. If the file doesn’t exist, it’s created. More access modes on page 201 of your book
Selected Pickle Functions dump(object, file, [,bin]) Writes pickled version of object to a file. If bin is True, object is written in binary format. If bin is False, object is written in less efficient, but more human-readable text format. The default is False load(file) Unpickles and returns the next pickled object in file
Simple Example variety = ["sweet", "hot", "dill"] # Create the list file = open("myPickle.dat", "wb") # Create the binary file pickle.dump(variety, file) # Write the list to file file.close() # Close the file file = open(PICKLE_PATH, "rb") # Open the file for read variety = pickle.load(file) # Read the file print("Variety: ", variety) # Print the list
Shelve Shelve also stores binary data Used for object persistence When you shelve an object, you must give a key by which the object is known This way, shelve becomes a database of stored values, any of which can be accessed at any time You must use ‘import shelve’ to gain access to the Python shelve code
Selected Shelve Access Modes “c” Open a file for reading or writing. If the file doesn’t exist it is created. “n” Create a new file for reading or writing. If the file exists, it’s contents are overwritten. “r” Read from a file. If the file doesn’t exist, Python will complain with an error.
Simple Shelve Example file = shelve.open(“foo.dat”, “n”) # Create the file file[“baseballScores”] = { “Rangers” : 1, “Astros” : 2} # Write file.sync() # Flush to disk file.close() # Close the file file = shelve.open(“foo.dat”, “r”) # Open the file print(file[“baseballScores”]) # Access by key
Complete Examples http://jbryan2.create.stedwards.edu/cosc1323/binaryFiles.txt