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 ,如需转载请自行联系原作者
相关文章
|
6天前
|
数据库连接 Python
超越`open()`:深入理解Python的`with`语句
超越`open()`:深入理解Python的`with`语句
188 99
|
13天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
195 100
|
13天前
|
开发者 Python
Python中的f-string:高效字符串格式化的利器
Python中的f-string:高效字符串格式化的利器
236 99
|
16天前
|
Python
Python中的f-string:更优雅的字符串格式化
Python中的f-string:更优雅的字符串格式化
|
16天前
|
开发者 Python
Python f-string:高效字符串格式化的艺术
Python f-string:高效字符串格式化的艺术
|
3月前
|
监控 算法 数据处理
Python 3.14七大新特性总结:从t-string模板到GIL并发优化
本文基于当前最新的beta 2版本,深入分析了Python 3.14中的七项核心新特性。
116 4
Python 3.14七大新特性总结:从t-string模板到GIL并发优化
|
2月前
|
Python
Python中的f-string:更简洁的字符串格式化
Python中的f-string:更简洁的字符串格式化
215 92
|
12月前
|
存储 Java 索引
Python String详解!
本文详细介绍了Python中的字符串数据类型,包括其创建、访问、切片、反转及格式化等操作。文章涵盖字符串的基本概念、各种操作方法以及常用内置函数。通过多个示例代码展示了如何使用单引号、双引号和三重引号创建字符串,如何通过索引和切片访问与修改字符串内容,以及如何利用格式化方法处理字符串。此外,还介绍了字符串的不可变性及其在实际应用中的重要性。通过本文的学习,读者可以全面掌握Python字符串的使用技巧。
273 4
|
12月前
|
Go C++ Python
Python Tricks: String Conversion(Every Class Needs a ___repr__)
Python Tricks: String Conversion(Every Class Needs a ___repr__)
81 5

热门文章

最新文章

推荐镜像

更多