Python 学习笔记之 Numpy 库——文件操作

1. 读写 txt 文件

a = list(range(0, 100))
a = np.array(a) # a.dtype = np.int64
np.savetxt("filename.txt", a) 
b = np.loadtxt("filename.txt") # b.dtype = np.float64
  • savetxt 默认保存为 float64 格式的,注意保存和读取时 dtype 要一致,否则读出的数据可能会乱码。
    numpy.loadtxt
    numpy.savetxt

2. 读写二进制 bin 文件

a = list(range(0, 100))
a = np.array(a) # a.dtype = np.int64
a.tofile("filename.bin", a) 
b = np.fromfile("filename.bin") # b.dtype = np.int64

3. 读写 Numpy 特有 npy 格式文件

a = list(range(0, 100))
a = np.array(a) # a.dtype = np.int64
np.save("filename.npy", a) 
b = np.load("filename.npy") # b.dtype = np.int64
  • save 保存格式和数组的数据格式一致,注意保存和读取时 dtype 要一致,否则读出的数据可能会乱码。
    numpy.save
    numpy.load

4. 读写字符串文件


file.txt

123 456
aaa
bbb
ccc
ddd

a = np.genfromtxt('file.txt', dtype='str', skip_header=1)

  • 跳过开头第一行,以字符串读取文件,a = array(['aaa', 'bbb', 'ccc', 'ddd'], dtype='<U3')

file.txt

123  aaa
456 bbb
789 ccc

a = np.genfromtxt('file.txt', dtype=None)
a[0][0] = 123 # <class 'numpy.int64'>
a[0][0] = b'aaa' # <class 'numpy.bytes_'>
a[0][0].decode() = 'aaa' # <class 'str'>

获取更多精彩,请关注「seniusen」!
这里写图片描述

原文地址:https://www.cnblogs.com/seniusen/p/9734864.html