You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python保存目录提取特征时open函数正确模式选择及报错解决

解决write()参数类型错误与numpy数组无损存储问题

首先,你遇到的"write() argument must be str, not numpy.ndarray"报错原因很明确:file.write()方法只能接受字符串类型的输入,但你直接传入了numpy数组,自然会触发类型错误。

关于你问的open语句用什么模式才能无损保存数据——其实模式只是实现细节的一部分,更关键的是要把numpy数组转换成适合存储的格式,同时完整保留所有原始信息。下面给你几种实用的解决方案:

最推荐:用numpy自带的save()/load()

这是专门为numpy数组设计的存储方案,完全无损,还能自动保留数组的形状、数据类型等元信息,用法也最简单,甚至不需要手动处理文件打开:

import numpy as np

# 替换你原来的文件操作代码
np.save(f'/home/rehan/predictions/bottleneck_features_train_{i}.npy', bottleneck_features_train)

# 后续需要加载数据时
loaded_features = np.load('/home/rehan/predictions/bottleneck_features_train_0.npy')

这种方式会自动以二进制格式存储,不需要你指定open的模式,numpy会帮你处理所有细节。

手动管理文件的方案

如果你一定要自己控制文件的打开和写入,那么需要用二进制写入模式'wb',配合以下两种方法:

方法1:使用pickle序列化

pickle可以把几乎所有Python对象(包括numpy数组)序列化为二进制数据:

import pickle

# 保存
with open(f'/home/rehan/predictions/bottleneck_features_train_{i}.pkl', 'wb') as file:
    pickle.dump(bottleneck_features_train, file)

# 加载
with open(f'/home/rehan/predictions/bottleneck_features_train_{i}.pkl', 'rb') as file:
    loaded_features = pickle.load(file)

方法2:使用numpy的tofile()

这种方式会把数组的原始二进制数据写入文件,但需要你记住数组的形状和数据类型,加载时要手动恢复:

# 保存
with open(f'/home/rehan/predictions/bottleneck_features_train_{i}.bin', 'wb') as file:
    bottleneck_features_train.tofile(file)

# 加载(需要指定原数组的dtype和shape)
loaded_features = np.fromfile('/home/rehan/predictions/bottleneck_features_train_0.bin', dtype=np.float32).reshape(4,4,6)

总结

  • 绝对不要用文本模式('w')直接写numpy数组,这既会触发类型错误,也会丢失关键数据信息
  • 优先选择np.save(),简单高效且完全无损
  • 手动操作的话,必须用二进制模式'wb',配合pickle或tofile()实现存储

内容的提问来源于stack exchange,提问作者Rehan Aziz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:49:38