Total Pageviews

2016/04/04

[Python] Using Pickle to read/write file

Using pickle is straightforward: import the required module, then use dump() to save your data and, some time later, load() to restore it. 

The only requirement when working with pickled files is that they have to be opened in binary access mode

Here is the code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
''' utilize pickle to write data into file '''
def writeFileWithPickle(path, file, data):
    pickle.dump(data, open(path + '/' + file, 'wb'))

''' utilize picke to read data from file '''
def readFileWithPickle(path, file):
    return pickle.load(open(path + '/' + file, 'rb'))

''' utilize pickle to append data to existing file '''
def appendDataWithPickle(path, file, data):
    try:
        with open(path + '/' + file, 'rb') as fileObject:
            list = pickle.load(fileObject)
            for item in data:
                list.append(item)
            writeFileWithPickle(path, file, list)
    except pickle.PickleError as err:
        print('Fail to append data. Error:' + str(err))
    finally:
        if 'fileObject' in locals():
            fileObject.close()


Reference
[1] http://pythontips.com/2013/08/02/what-is-pickle-in-python/


No comments: