codingdir logo sitemap sitemap |

Write a binary integer or string to a file in python

By : , Category : python

This would write your string to a file:

with open('myfile', 'w') as fobj:
ReLated :

I found answer for this question in using another encoding, and writing bytes:

file = open('file.bin','wb')
cur = 0
while cur < len(code):
    c = int(code[cur:cur+8], 2)
    file.write(bytes(chr(c), 'iso8859-1'))
    cur += 8

I wrote string with 0 and 1: 000101101100000000010010110000010011000000010010001000100000000000010111110000110100001100010001

And if i open file with notepad I will see АБ0" ГC some symbols not shown... but if i will open file in hex redactor I will see:

00010110 11000000 00010010 11000001 00110000 00010010 00100010 00000000 00010111 11000011 01000011 00010001

Best 96 bits!

It seems you need struct:

import struct
import numpy as np # for random string of ones and zeros

def chunks(s):
    for i in xrange(0, len(s), 32):
         yield s[i:i+32]

s =  ''.join(str(np.random.randint(2)) for x in xrange(32*2))
ints = (int(x, 2) for x in chunks(s)) # convert string from binary repr to integers
bins = (struct.pack('I', i) for i in ints) # pack to unsigned ints


>>> s
>>> ''.join(bins)

Note that I format is unsigned int in native format, you can specify byte order expicetely, with >I being big-endian int32, and <I little-endian (note reversed order of 4-byte sequences):

>>> bi_bins = (struct.pack('>I',  i) for i in ints)
>>> ''.join(bi_bins)

As @Ben just said, use fwrite. Supposing your uint32 variable is stored in A which is of type uint32, and supposing you want to write to a file called test.txt, simply do this:

fid = fopen('test.txt', 'w'); %// Open test.txt for writing
fwrite(fid, A, 'uint32'); %// Write this single uint32 number to file
fclose(fid); %// Close the file to register the changes

Try using string format method:


Message :
Login to Add Your Comments .
How to disable registered OpenCL platforms on Windows?
Is Observable broken in Angular 2 Beta 3?
Cross-thread operation not valid when using Invoke
How to pass an IEnumerable or queryable list of properties from Controller to View
Finding numbers after a certain keyword using Python
Pocketsphinx recognizes random phrases in a silence
Passing non-thread-safe objects through thread-safe containers
React scroll nav
BizTalk WCF-BasicHttp Adapter does not allow Empty string for Service Certificate Props
Why property ''cause" of Exception is repeating forever?
Privacy Policy 2017 © All Rights Reserved .