-1

Possible Duplicate:
How to write individual bits to a text file in python?

I have been searching, trying to find a way to simply read and write bits to/from a file. Most of the things I have found have just showed ways to convert characters to binary. such as:

    >>> byte = 'a'
    >>> byte = ord(byte)
    >>> byte = bin(byte)
    >>> print byte
    '0b1100001'

This isn't what I want. I am looking to manipulate the actual binary in the file. I dont want to use extra modules, just standard python 2.7. Any help would be appreciated.

1
  • Yea i saw this and it seemed similar but im looking for a simpler explanation maybe and a clearer answer. Commented Aug 26, 2012 at 0:57

1 Answer 1

0

open files in binary mode, using 'r+b':

>>> f=open('data.txt','wb')
>>> f.write('abcd')
>>> f.close()
>>> f=open('data.txt','rb')
>>> [bin(ord(x)) for x in f.read(4)]        #read(4) to read 4 bytes
['0b1100001', '0b1100010', '0b1100011', '0b1100100']
>>> 
Sign up to request clarification or add additional context in comments.

1 Comment

not sure about python 2.7 but in python 3.x you can do f.write(b'1100001')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.