[Tutor] pickle.dump yielding awkward output
davea at davea.name
Mon Feb 4 00:48:35 CET 2013
(top-posting and offline response fixed)
On Sun, Feb 3, 2013 at 11:07 PM, Dave Angel <davea at davea.name> wrote:
>> On 02/03/2013 02:26 PM, Spyros Charonis wrote:
>>> Hello Pythoners,
>>> I am experiencing a strange result with the pickle module when using it to
>>> write certain results to a separate file.
>>> In short, I have a program that reads a file, finds lines which satisfy
>>> some criteria, and extracts those lines, storing them in a list. I am
>>> trying to write this list to a separate file.
>>> The list of extracted lines looks like this:
>>> ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40
>>> ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51
>>> ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13
>>> The output stored from the call to the pickle.dump method, however, looks
>>> like this:
>>> S'ATOM 1 N GLN A 1 29.872 13.384 54.754 1.00 60.40
>>> N \r\n'
>>> aS'ATOM 2 CA GLN A 1 29.809 11.972 54.274 1.00 58.51
>>> C \r\n'
>>> aS'ATOM 3 C GLN A 1 28.376 11.536 54.029 1.00 55.13
>>> C \r\n'
>>> The code I am using to write the output to an external file goes as
>>> def export_antibody_chains():
>>> ''' EXPORT LIST OF EXTRACTED CHAINS TO FILE '''
>>> chains_file = open(query + '_Chains', 'wb')
>>> pickle.dump(ab_chains, chains_file) # ab_chains is global
>>> Does anyone know why the strings lp0, S', aS' are showing up?
>> Pickle stores the type of each variable, as well as the value, and stores
>> it in a way as to make it easy to "unpickle" it.
On 02/03/2013 06:17 PM, Spyros Charonis wrote:
> Thank you Dave,
> Is there any way to circumvent this so that I get the list rendered
> normally? Many thanks.
You'd better define "normally." Pickle's output is normal for pickle.
Perhaps you want the values to be human readable instead.
One possibility of many: If you know that all the values in the list
are strings, and you want to produce a text file, with one such string
per line, then try:
outfile = open( "filename.txt", 'wt")
for line in mylist:
outfile.write( line + "\n")
There are ways to clean that up, but since you haven't specified your
python version, that'll do for a first attempt.
More information about the Tutor