详解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设计】。

相关文章

如何在python中使用selenium的示例

最近基于selenium写了一个python小工具,记录下学习记录,自己运行的环境是Ubuntu 14.04.4, Python 2.7,Chromium 49.0,ChromeDriv...

python实现二维码扫码自动登录淘宝

python实现二维码扫码自动登录淘宝

一个小项目自动登录淘宝联盟抓取数据,由于之前在Github上看过类似用Python写的代码因此选择用Python来写,第一次用Python正式写程序还是被其“简单”所震撼,当然用的时候还...

使用Python OpenCV为CNN增加图像样本的实现

使用Python OpenCV为CNN增加图像样本的实现

我们在做深度学习的过程中,经常面临图片样本不足、不平衡的情况,在本文中,作者结合实际工作经验,通过图像的移动、缩放、旋转、增加噪声等图像变换技术,能快速、简便的增加样本数量。 本文所有案...

python+Django实现防止SQL注入的办法

先看看那种容易被注入的SQL id = 11001 sql = """ SELECT id, name, age FRO...

python创建关联数组(字典)的方法

本文实例讲述了python创建关联数组(字典)的方法。分享给大家供大家参考。具体分析如下: 关联数组在python中叫字典,非常有用,下面是定义字典的两种方法 # Dictionar...