Search code examples
pythonencodingbluetoothgetobex

Convert and save string to binary file in Python


I'm using PyOBEX to exchange binary files (e.g. images etc.) between my computer (Windows 7) and my phone (Android). However, when I use get() to get a file from my phone, it arrives on my computer as a str. I tried using the chardet module to find out what encoding to use to decode it and eventually turn it into a binary file, but it returned None. type() says that it's a str.

The code is the following:

import bluetooth
import BTDeviceFinder
import PyOBEX.client

name = "myDevice"
address = BTDeviceFinder.find_by_name(name)
port = BTDeviceFinder.find_port(address)
client = PyOBEX.client.BrowserClient(address, port)
client.connect()
a, b = client.get("pic.jpg")

where a is the header (that comes with a file sent via OBEX) and b is the actual file object. b looks something like this: https://drive.google.com/file/d/0By0ywTLTjb3LaFJaM2hWVEdBakE/view?usp=sharing

The PyOBEX documentation or Python forums say nothing about what encoding is used with get().

Do you know how to turn this string into binary data that can be used with write() and then saved in the original file format (i.e. .jpg)?


Solution

  • In python 2.7 strings represent raw bytes (this changes in python 3)

    You simply need to save the data to a binary type file:

    with open('file.jpg', 'wb') as handle:
        handle.write(data_string)
    

    Here is a link to the python doc on open:

    https://docs.python.org/2/library/functions.html#open

    Note that the "b" represents binary.

    Again, this is assuming Python 2.7