Separate binary data (blobs) in csv files
<p>Is there any safe way of mixing binary with text data in a (pseudo)csv file?</p>

<p>One naive and partial solution would be:</p>

<ul>
<li>using a compound field separator, made of more than one character (e.g. the <code>\a\b</code> sequence for example)</li>
<li>saving each field as either text or as binary data would require the parser of the pseudocsv to look for the <code>\a\b</code> sequence and read the data between separators according to a known rule (e.g. by the means of a known header with field name and field type, for example)</li>
</ul>

<p>The core issue is that binary data is not guaranteed to not contain the <code>\a\b</code> sequence somewhere inside its body, before the actual end of the data.</p>

<p>The proper solution would be to save the individual blob fields in their own separate physical files and only include the filenames in a .csv, but this is not acceptable in this scenario.</p>

<p>Is there any proper and safe solution, either already implemented or applicable given these restrictions?</p>

<p>If you need everything in a single file, just use one of the methods to encode binary as printable ASCII, and add that results to the CSV vfieds (letting the CSV module add and escape quotes as needed).</p>

<p>One such method is <code>base64</code> - but even on Python's base64 codec, there are more efficient codecs like base85 (on newer Pythons, version 3.4 and above, I guess).</p>

<p>So, an example in Python 2.7 would be:</p>

<pre><code>import csv, base64

import random
data = b''.join(chr(random.randrange(0,256)) for i in range(50))

writer = csv.writer(open("testfile.csv", "wt"))
writer.writerow(["some text", base64.b64encode(data)])
</code></pre>

<p>Of course, you have to do the proper base64 decoding on reading the file as well - but it is certainly better than trying to create an ad-hoc escaping method.</p>

python csv blob binaryfiles export-to-csv