python字符串转二进制文件,在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)?

解决方案

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:

Note that the "b" represents binary.

Again, this is assuming Python 2.7

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值