using marshal module

Quinn Dunkan quinn at krone.ugcs.caltech.edu
Wed Feb 2 05:39:22 CET 2000


On Wed, 2 Feb 2000 17:17:08 +1300, Christine Davis <c.davis at actrix.co.nz> wrote:
>I have this feeling I may be missing out something important, but silly.

That feeling is about to e vindicated :)

>Cheers,
>Christine
>
>
>Here is the piece of broken code:
>
># open the file
>fp = open(filename)
>datastuff = marshal.load(fp)
>
># change the field
>datastuff['field'] = 'new string of stuff'
>
># "write it back to the file"
># also tried "marshal.dump(datastuff, fp)" which didn't work either
>marshal.dump(datastuff['field'], fp)
>
># close the file
>fp.close()

When you opened the file, you opened it in read mode (think
fp = fopen(filename, "r"); in C).  Now, when you tried to dump your data to
it, marshal should have thrown an IOError, but instead it silently didn't
write anything.  This seems unpython-like and a problem with marshal, to me.

What you want to do is either:
fp = open(filename, 'r+b') # b in case it gets run on windows
and then
fp.seek(0)
before dump.

Or:
fp.close()
fp.open(filename, 'wb')
before dump.

Also, marshal.dump(datastuff['field'], fp) will store the string 
'new string of stuff' to filename, which is probably not what you want.



More information about the Python-list mailing list