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 thestrtype isalreadyencoded bytes. So on Python 3 you'd use: somestring = 'abcd' with open("test.bin...
You shouldjust write your string: somestring ='abcd'withopen("test.bin","wb")asfile: 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\nnewlines to the line separat...
在Python 中,可以将二进制字符串保存为二进制文件。这可以通过打开一个文件,并使用write()方法来实现。下面是一个示例: binary_string=b'Hello, World!'withopen("binary_file.bin","wb")asf:f.write(binary_string) 1. 2. 3. 以上代码将二进制字符串b'Hello, World!'保存为名为 “binary_file.bin” ...
somestring ='abcd'withopen("test.bin","wb")asfile: 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\nnewlines to the line separator standard for your platform; e....
file = open("binary_file.bin", "wb") string = "Hello, World!" byte_string = string.encode("UTF-8") file.write(byte_string) file.close() ``` 以上就是使用Python将字符串写入二进制文件的方法。接下来,我们来进行一些扩展的讨论。 一、写入多行字符串 如果要写入多行字符串,可以使用换行符将...
a file in a binary mode, the returned class varies: in read binary mode, it returns a BufferedReader; in write binary and append binary modes, it returns a BufferedWriter, and in read/write mode, it returns a BufferedRandom. It is also possible to use a string or bytearray as a file...
使用模式为 rb 或wb 的open() 函数来读取或写入二进制数据。比如: # Read the entire file as a single byte string with open('somefile.bin', 'rb') as f: data = f.read() # Write binary data to a file with open('somefile.bin', 'wb') as f: f.write(b'Hello World') __EOF__ ...
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有...
' f.write(data) f.close() with open("二进制文本文件.txt", "wb") as ...
300)data=sensor_obj.toBytes()myfile.write(data)sleep(1)deffromFile(filename):"""从二进制文件...