Python内存中读写字符串与二进制数据及浮点转换示例

Evan
Evan
发布时间:2026-10-13 | 2人浏览过
原创

本文介绍了Python中利用io模块的StringIO和BytesIO类在内存中高效读写字符串及二进制数据的方法,并通过numpy库演示了如何将二进制文件数据读取并转换为float32类型。内容涵盖基础内存操作及具体的数组处理代码示例,适用于需要高性能数据处理的场景。

Python内存中读写字符串与二进制数据

以下直接展示相关代码实现。


# 利用python在内存中读写str和二进制数据
from io import StringIO
from io import BytesIO
 
f = StringIO()
print(f.write('hello ')) # 6
print(f.write('world!')) # 6
print(f.getvalue()) # hello world!
 
f = BytesIO()
print(f.write('中文'.encode('utf-8'))) # 6
print(f.getvalue()) # b'\xe4\xb8\xad\xe6\x96\x87'

补充知识:Python中将二进制数据转换为浮点数(float)的处理方式。

具体代码示例如下。

二进制数据转换为Float的实现


# -*- coding: utf-8 -*-
"""
Created on Tue Dec 3 14:38:04 2019
@author: xuguanghui
"""
 
import numpy as np
 
mlplib_label = r"C:\Users\xuguanghui\Desktop\106421_mlplib.lab"
train_label = r"C:\Users\xuguanghui\Desktop\106421_train.lab"
mlplib_txt = r"C:\Users\xuguanghui\Desktop\106421_mlplib.txt"
train_txt = r"C:\Users\xuguanghui\Desktop\106421_train.txt"
 
mlplib_lab = np.fromfile(mlplib_label, dtype=np.int32).reshape(-1, 892)
train_lab = np.fromfile(train_label, dtype=np.float32).reshape(-1, 892)
 
np.savetxt(mlplib_txt, mlplib_lab, fmt='%d')
np.savetxt(train_txt, train_lab, fmt='%d')

以上关于Python在内存中读写字符串及二进制数据的代码分享完毕,希望能为读者提供参考。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表