Skip to main content
gamedev.net
🔒 Locked

Writing a binary file in Python?

Started by Missle Launch Jun 6, 2006 at 10:13 PM 8 replies 1.4k views
Original Post
Missle Launch
Missle Launch
My attempts using write() have failed miserably. Do I need to get a specific library?
Fruny
Fruny
You might want to use the struct module.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
smr
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.

f = file("file.bin", "wb") # w: write, b: binary
f.write(data)
Oluseyi
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]
smr
smr
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.
Missle Launch
Missle Launch
I had never heard of the struct-module, before: I'll go investigate it.
bytecoder
bytecoder
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 cPickleclass 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]
Missle Launch
Missle Launch
bytecoder, you are a saint. I very much appreciate your graciousness, here.
Fruny
Fruny
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.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.