Sign in to follow this  
Missle Launch

Writing a binary file in Python?

Recommended Posts

Could you post some source code? Without seeing it, my first guess would be that you aren't opening the file in binary mode.

f = file("file.bin", "wb") # w: write, b: binary
f.write(data)

Share this post


Link to post
Share on other sites
Quote:
Original post by smr
Could you post some source code? Without seeing it, my first guess would be that you aren't opening the file in binary mode.

Actually, opening a file in "binary" mode is only meaningful under Windows, for starters. Secondly, file.write will always perform a character-mode write. Now, you can use it to write the data in binary format, but you have to pack that data into a string first.

The struct module exists for this specific reason. Use it. [smile]

Share this post


Link to post
Share on other sites
Quote:
Original post by Oluseyi
Quote:
Original post by smr
Could you post some source code? Without seeing it, my first guess would be that you aren't opening the file in binary mode.

Actually, opening a file in "binary" mode is only meaningful under Windows, for starters. Secondly, file.write will always perform a character-mode write. Now, you can use it to write the data in binary format, but you have to pack that data into a string first.

The struct module exists for this specific reason. Use it. [smile]


I also assume he's using windows :D

I didn't mention struct since Fruny had already and didn't want to steal his thunder.

Share this post


Link to post
Share on other sites
You might also be interested in the cPickle module if this is for object serialization. If this data is only going to be accessed from your python program, it's much easier:

import cPickle

class Game(object):
...

game = Game()
cPickle.dump(game, open("game.dat", "w"))

...

game = cPickle.load(open("game.dat"))


[Edited by - bytecoder on June 7, 2006 5:40:27 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by Anonymous Poster
How do I set the endian of a file?


Files have no endianness. The data does. See the struct module documentation.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this