Write a binary integer or string to a file in python

前端 未结 5 1819
梦毁少年i
梦毁少年i 2020-12-16 00:46

I have a string (it could be an integer too) in Python and I want to write it to a file. It contains only ones and zeros I want that pattern of ones and zeros to be written

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 01:26

    Alright, after quite a bit more searching, I found an answer. I believe that the rest of you simply didn't understand (which was probably my fault, as I had to edit twice to make it clear). I found it here.

    The answer was to split up each piece of data, convert them into a binary integer then put them in a binary array. After that, you can use the array's tofile() method to write to a file.

    from array import *
    
    bin_array = array('B')
    
    bin_array.append(int('011',2))
    bin_array.append(int('010',2))
    bin_array.append(int('110',2))
    
    with file('binary.mydata', 'wb') as f:
        bin_array.tofile(f)
    

提交回复
热议问题