python在内存中读写str和二进制数据的方法

发布时间:2020-07-31 09:46:59 作者:小猪
来源:亿速云 阅读:233

这篇文章主要讲解了python在内存中读写str和二进制数据的方法,内容清晰明了,对此有兴趣的小伙伴可以学习一下,相信大家阅读完之后会有帮助。

我就废话不多说了,还是直接看代码吧!

# 利用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

看代码吧!

# -*- 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在内存中读写str和二进制数据的方法有进一步的了解,如果还想学习更多内容,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. python 在内存中读写:StringIO / BytesIO
  2. str()和repr()在Python中的区别是什么

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python str

上一篇:python中打出引号的方法

下一篇:Python之初识面向对象

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》