[BangPypers] writing file with random extension to sd card using python

Krishnan Nagarajan krishnan.nagarajan at gmail.com
Thu Oct 26 23:51:46 EDT 2017


Hi,
Refer :
https://stackoverflow.com/questions/27238680/writing-integers-in-binary-to-file-in-python


With Python 3 you can do the following:

i = 6277101735386680763835789423176059013767194773182842284081with
open('out.bin', 'wb') as file:
    file.write((i).to_bytes(24, byteorder='big', signed=False))
with open('out.bin', 'rb') as file:
    j = int.from_bytes(file.read(), byteorder='big')
print(j)

Output:

$ python3 tiny.py6277101735386680763835789423176059013767194773182842284081


What this tells us :

While writing int (or any data including string - as UTF) as binary data to
a file, you need to conver (and encode) it to bytes;
In this case we need to specify the width as well.

While reading such binary data from the file, you need to correspondingly
decode (interpret) the data while converting into python data type (int /
even string / unicode).
Again sidth needs to be specified here to disctate how many bytes to use to
convert to an int.







On Fri, Oct 27, 2017 at 7:11 AM, Sushrut Deshpande <dsushrut at qvestron.com>
wrote:

> I think you shud open file as binary write and try to write the integer
> after converting it to utf-8
>
> Best Regards,
> Sushrut Deshpande
> Founder - Qvestron Systems Pvt. Ltd.,
> dsushrut at qvestron.com
> +91 9513333160
>
>
>
> On 27 Oct 2017 00:20, at 00:20, Ajinkya Bobade <ajinkyabobade93 at gmail.com>
> wrote:
> >Hello,
> >This is my first question on this forum point me in a right way if I
> >posted
> >in a wrong place. That aside I am trying to write a file with '.bag
> >' extension to sd card( .bag is used in Ross programming).
> >
> >I wrote a code to write a simple integer to disk as shown
> >
> >
> >file = open("/path/to/file", 'w')
> >x = 1
> >
> >while True:
> >    x = x + 1
> >    print(x)
> >    file.write(str(x))
> >    file.flush()
> >
> >in this code I could not write file.write(x). Why is this?If I want to
> >store a file(' as it is') on this disk without converting it into
> >string
> >what should I do?
> >_______________________________________________
> >BangPypers mailing list
> >BangPypers at python.org
> >https://mail.python.org/mailman/listinfo/bangpypers
> _______________________________________________
> BangPypers mailing list
> BangPypers at python.org
> https://mail.python.org/mailman/listinfo/bangpypers
>


More information about the BangPypers mailing list