python string写入二进制文件——直接wb形式open file,再write string即可

简介:
oteaccepted

You misunderstood what \xhh does in Python strings. Using \x notation in Python strings is just syntax to produce certain codepoints.

You can use '\x61' to produce a string, or you can use 'a'; both are just two ways of saying give me a string with a character with hexadecimal value 61, e.g. the a ASCII character:

>>> '\x61'
'a' >>> 'a' 'a' >>> 'a' == '\x61' True

The \xhh syntax then, is not the value; there is no \ and no x and no 6 and 1 character in the final result.

You should just write your string:

somestring = 'abcd' with open("test.bin", "wb") as file: file.write(somestring)

There is nothing magical about binary files; the only difference with a file opened in text mode is that a binary file will not automatically translate \n newlines to the line separator standard for your platform; e.g. on Windows writing \n produces \r\n instead.

You certainly do not have to produce hexadecimal escapes to write binary data.

On Python 3 strings are Unicode data and cannot just be written to a file without encoding, but on Python the str type is already encoded bytes. So on Python 3 you'd use:

somestring = 'abcd' with open("test.bin", "wb") as file: file.write(somestring.encode('ascii'))

or you'd use a byte string literal; b'abcd'.











本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/bonelee/p/6497055.html ,如需转载请自行联系原作者
相关文章
|
23天前
|
Python
【python】python跨文件使用全局变量
【python】python跨文件使用全局变量
|
1月前
|
监控 数据处理 索引
使用Python批量实现文件夹下所有Excel文件的第二张表合并
使用Python和pandas批量合并文件夹中所有Excel文件的第二张表,通过os库遍历文件,pandas的read_excel读取表,concat函数合并数据。主要步骤包括:1) 遍历获取Excel文件,2) 读取第二张表,3) 合并所有表格,最后将结果保存为新的Excel文件。注意文件路径、表格结构一致性及异常处理。可扩展为动态指定合并表、优化性能、日志记录等功能。适合数据处理初学者提升自动化处理技能。
22 1
|
7天前
|
存储 Python
用Python实现批量下载文件——代理ip排除万难
用Python实现批量下载文件——代理ip排除万难
|
7天前
|
JSON 关系型数据库 数据库
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
《Python 简易速速上手小册》第6章:Python 文件和数据持久化(2024 最新版)
34 0
|
7天前
|
数据挖掘 索引 Python
Python 读写 Excel 文件
Python 读写 Excel 文件
12 0
|
7天前
|
数据安全/隐私保护 Python
Python文件与目录操作:面试中的高频考点
【4月更文挑战第15天】本文介绍了Python文件和目录操作的面试重点,包括文件的读写、目录遍历及权限管理。强调了文件关闭、异常处理、特殊文件判断以及权限位和权限字符串的理解。提供了代码示例,如读写文件、遍历目录和更改文件权限,帮助读者在面试中表现出色。掌握这些技能将对编程求职之路大有裨益。
17 0
|
9天前
|
存储 监控 开发工具
对象存储OSS产品常见问题之python sdk中的append_object方法支持追加上传xls文件如何解决
对象存储OSS是基于互联网的数据存储服务模式,让用户可以安全、可靠地存储大量非结构化数据,如图片、音频、视频、文档等任意类型文件,并通过简单的基于HTTP/HTTPS协议的RESTful API接口进行访问和管理。本帖梳理了用户在实际使用中可能遇到的各种常见问题,涵盖了基础操作、性能优化、安全设置、费用管理、数据备份与恢复、跨区域同步、API接口调用等多个方面。
40 9
|
23天前
|
C++ Python
【C++/Python】C++调用python文件
【C++/Python】C++调用python文件
|
24天前
|
JSON 数据处理 数据格式
Python中的文件读写操作详解
【4月更文挑战第2天】在Python中,文件读写操作是数据处理和程序开发的重要部分。通过文件,我们可以将信息持久化地保存在磁盘上,并在需要时读取和使用这些数据。Python提供了丰富的内置函数和模块,使得文件读写变得简单而高效。本文将详细介绍Python中文件读写的基本操作和常用方法。
|
1月前
|
开发者 Python
Python语言的文件及目录访问
Python语言的文件及目录访问