89

At times, I've seen .pickle, .pck, .pcl, and .db for files that contain Python pickles, but I am unsure what is the most common or best practice. I know that the latter three extensions are also used for other things.

The related question is: What MIME type is preferred for sending pickles between systems using a REST API?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Raymond Hettinger
  • 182,864
  • 54
  • 321
  • 419
  • 4
    What's funny is that I'm sure once upon a time I've used .pkl. – idjaw Nov 05 '16 at 00:21
  • 2
    For some reason this is not in the Python 3 doc, but in the Python 2 doc and specifying `pkl` -> https://docs.python.org/2/library/pickle.html#example – idjaw Nov 05 '16 at 00:22
  • 4
    Avoid pickle wherever possible. There's a reason the docs warn against using pickle - it's not safe, it's never been safe, and it never will be safe. Use the json module instead. – KingRadical Nov 05 '16 at 01:32
  • @KingRadical could you give some alternatives? – Rafa Nogales Jun 14 '20 at 16:23
  • 1
    @RafaNogales msgpack seems a good binary alternative https://pypi.org/project/u-msgpack-python/ – giuliano-oliveira Sep 26 '20 at 12:36

1 Answers1

104

Python 2

From the Python 2 documentation, while serializing (i.e. writing to a pickle file), use:

output = open('data.pkl', 'wb')

I would choose .pkl as the extension when using Python 2.

Python 3

The example in the Python 3 documentation now uses .pickle as the file extension for serialization:

with open('data.pickle', 'wb') as f:
    pickle.dump(...)

The MIME type preferred for sending pickles from martineau's comment below:

application/octet-stream

See What is the HTTP "content-type" to use for a blob of bytes?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
TheoretiCAL
  • 15,550
  • 7
  • 33
  • 61
  • `text/plain` might not work depending on the pickle protocol being used — protocol version 0 is the only one that's ASCII. – martineau Nov 05 '16 at 01:15
  • 2
    That said, I think `application/octet-stream` would be better regardless of the protocol — see question [_What is the HTTP “content-type” to use for a blob of bytes?_](http://stackoverflow.com/questions/13223855/what-is-the-http-content-type-to-use-for-a-blob-of-bytes) – martineau Nov 05 '16 at 01:28