python 利用 np.load() 读取.npy文件

如何读取.npy文件呢?

需要利用 numpy.load() 函数进行读取。

具体实例如下:

import numpy as np

a = np.load('DataBaker-duration-000001.npy')
print(a)  ## [11  8  8 10 13  6 11 17  8 15 15  7 14 10 17]

### 使用 `np.fromfile` 读取 `.npy` 文件 尽管 NumPy 提供了专门用于处理 `.npy` 文件的功能函数,如 `numpy.load()`,但有时开发者可能希望尝试其他方法来加载这些文件。然而需要注意的是,`.npy` 是一种二进制格式,其头部包含了元数据信息(例如数组形状、数据类型等),因此直接通过 `np.fromfile` 来解析可能会遇到一些复杂情况。 以下是关于如何使用 `np.fromfile` 的说明以及注意事项: #### 方法描述 `np.fromfile` 主要设计用来从简单的二进制文件读取连续的数据流,而 `.npy` 文件不仅包含实际数据部分还附加有头信息。如果强制使用 `np.fromfile` 解析 `.npy` 文件,则需要手动跳过该文件的头部并正确解释后续的内容[^1]。 下面是一个示例代码展示如何实现这一过程: ```python import numpy as np def read_npy_with_fromfile(file_path): with open(file_path, 'rb') as f: # 跳过 .npy 文件的头部 (简单方式假设固定大小) magic_string = f.read(6) # 魔术字符串 '\x93NUMPY' version_major, version_minor = np.frombuffer(f.read(2), dtype=np.uint8) header_len_size = int(version_major >= 2) * 2 + 2 header_length = np.frombuffer(f.read(header_len_size), dtype=(np.int16 if version_major < 2 else np.uint32))[0] # 读取头部字典 header_str = f.read(header_length).decode('ascii') header_dict = dict(item.split(':') for item in filter(None, header_str.strip().split(','))) shape = tuple(map(int, header_dict['shape'].strip('()').split(','))) if '()' not in header_dict['shape'] else () dtype = np.dtype(header_dict['dtype']) data_start_position = f.tell() result_array = np.fromfile(file_path, dtype=dtype, offset=data_start_position) return result_array.reshape(shape) # 示例调用 array_loaded = read_npy_with_fromfile('./example.npy') print(array_loaded) ``` 上述脚本展示了如何绕开标准库中的 `load` 函数自行解读 `.npy` 文件的过程。不过这种方法较为繁琐且容易出错,推荐优先考虑官方支持的方式即利用 `numpy.load()` 加载 `.npy` 数据[^2]。 #### 官方建议替代方案 对于大多数场景来说,最简便可靠的办法还是采用内置工具完成操作: ```python data = np.load('your_file.npy') ``` 此单行命令即可高效准确地恢复存储于磁盘上的 ndarray 对象及其属性设置。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值