How to modify the data in a binary file?

Jim Brown python7946 at gmail.com
Wed Jul 2 14:05:39 CEST 2008


Hi all, I'm a Python newbie, so please pardon me if my question may look a
little silly. :)

I want to modify a binary file p.data (which has some C-style "short"
integers -- 16-bit integers) in such a way:
The bit m and bit n of every "short int" si in the file are set to 1, and
the left bits in si are not affected.

I.e, for the first short int in the file, I think the code would be:

import os
f = os.open("/root/p.data", os.O_RDWR)
str = os.read(f, 2)

#assume the short int in str is 0x0102, and I want to change it to 0x8182
(changing bit7 and bit15 to 1).
#how to change the str into a short int variable si??
???

si = (si & ~0x8080) | 0x8080

# how to change the si to a two-byte str?
???

os.lseek(f, 0, 0);
os.write(f, si)
os.close(f)


Thanks a lot!
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080702/998edd22/attachment.html>


More information about the Python-list mailing list