在Python中将字符串转换并保存为二进制文件 [英] Convert and save string to binary file in Python

查看:859
本文介绍了在Python中将字符串转换并保存为二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用PyOBEX在计算机(Windows 7)和手机(Android)之间交换二进制文件(例如图像等).但是,当我使用get()从手机中获取文件时,该文件以str的形式到达计算机.我尝试使用chardet模块来找出用于解码的编码,并最终将其转换为二进制文件,但它返回了None. type()表示它是str.

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.

代码如下:

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")

其中,a是标头(通过OBEX发送的文件随附),而b是实际的文件对象. b看起来像这样: https://drive.google.com/file/d/0By0ywTLTjb3LaFJaM2hWVEdBakE/view?usp = sharing

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

PyOBEX文档或Python论坛对get()所使用的编码没有任何说明.

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

您知道如何将字符串转换成可以与write()一起使用的二进制数据,然后以原始文件格式(即.jpg)保存吗?

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)?

推荐答案

在python 2.7中,字符串表示原始字节(在python 3中此更改)

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)

以下是打开时指向python文档的链接:

Here is a link to the python doc on open:

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

请注意,"b"代表二进制.

Note that the "b" represents binary.

同样,这是假设使用Python 2.7

Again, this is assuming Python 2.7

这篇关于在Python中将字符串转换并保存为二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆