详解Python list和numpy array的存储和读取方法

yipeiwu_com6年前Python基础

numpy array存储为.npy

存储:

import numpy as np
numpy_array = np.array([1,2,3])
np.save('log.npy',numpy_array )

读取:

import numpy as np
numpy_array = np.load('log.npy')

运行结果:

这里写图片描述

list存储为.txt

存储:

list_log = []
list_log.append([1,2,3])
list_log.append([4,5,6,7])
file= open('log.txt', 'w') 
  for fp in list_log:
    file.write(str(fp))
    file.write('\n')
file.close()

这样存储的结果list_log的每一行在txt也是分行的

运行结果:

这里写图片描述

这里写图片描述

读取:

file=open('log.txt', 'r')
list_read = file.readlines()

读出来list_read的结果仍然是一行一行的

运行结果:

这里写图片描述

.txt文件读取为int

在这里插入图片描述

label_path = 'C:/Users/leex/Desktop/label.txt'
file = open((label_path),'r')
label = [int(x.strip()) for x in file]
file.close()

运行结果:

在这里插入图片描述

如果不加int(),则读取的为字符串格式

在这里插入图片描述

还有一种常见的情况是label是以one-hot编码存储的

在这里插入图片描述

可以用np.loadtxt读取

import numpy as np
label_path = 'C:/Users/leex/Desktop/label.txt'
label = np.loadtxt(label_path, dtype=np.int64)

运行结果

在这里插入图片描述

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3中类的继承以及self和super的区别详解

python中类的继承: 子类继承父类,及子类拥有了父类的 属性 和 方法。 python中类的初始化都是__init__()。所以父类和子类的初始化方式都是__init__(),但是如...

python保存数据到本地文件的方法

1、保存列表为.txt文件 #1/list写入txt ipTable = ['158.59.194.213', '18.9.14.13', '58.59.14.21'] file...

使用Python给头像戴上圣诞帽的图像操作过程解析

使用Python给头像戴上圣诞帽的图像操作过程解析

前言 随着圣诞的到来,大家纷纷@官方微信给自己的头像加上一顶圣诞帽。当然这种事情用很多P图软件都可以做到。但是作为一个学习图像处理的技术人,还是觉得我们有必要写一个程序来做这件事情。而且...

django从请求到响应的过程深入讲解

django从请求到响应的过程深入讲解

django启动 我们在启动一个django项目的时候,无论你是在命令行执行还是在pycharm直接点击运行,其实都是执行'runserver'的操作,而ruserver是使用djan...

Python subprocess模块详细解读

Python subprocess模块详细解读

本文研究的主要是Python subprocess模块的相关内容,具体如下。 在学习这个模块前,我们先用Python的help()函数查看一下subprocess模块是干嘛的: DES...