Python Cookbook
Problem You need to create a temporary file or directory for use when your program executes. Afterward, you possibly want the file or directory to be destroyed. Solution The tempfile module has a variety of functions for performing this task. To make an unnamed temporary file, use tempfile.TemporaryFile:
On most Unix systems, the file created by TemporaryFile() is unnamed and won’t even have a directory entry. If you want to relax this constraint, use NamedTemporaryFile() instead.
As with TemporaryFile(), the resulting file is automatically deleted when it’s closed. If you don’t want this, supply a delete=False keyword argument.
Problem You need to serialize a Python object into a byte stream so that you can do things such as save it to a file, store it in a database, or transmit it over a network connection. Solution The most common approach for serializing data is to use the pickle module.
Problem You want to read or write data encoded as a CSV file. Solution For most kinds of CSV data, use the csv library.
Problem You want to read or write data encoded as JSON (JavaScript Object Notation). Solution The json module provides an easy way to encode and decode data in JSON.
The two main functions are json.dumps() and json.loads(), mirroring the interface used in other serialization libraries, such as pickle.
Problem You need to decode a string of hexadecimal digits into a byte string or encode a byte string as hex. Solution If you simply need to decode or encode a raw string of hex digits, use the binascii module.