tofile和fromfile数组内建函数

本文介绍如何使用NumPy的tofile和fromfile函数进行数组数据的二进制格式存储与读取。演示了如何正确设置数据类型和形状以确保数据一致性,并提供了示例代码。

numpy教程:基本输入输出和文件输入输出Input and output

使用数组的方法函数tofile可以方便地将数组中数据以二进制的格式写进文件。tofile输出的数据没有格式,因此用numpy.fromfile读回来的时候需要自己格式化数据

>>> a = np.arange(0,12)
>>> a.shape = 3,4
>>> a
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])
>>> a.tofile("a.bin")
>>> b = np.fromfile("a.bin", dtype=np.float) # 按照float类型读入数据
>>> b # 读入的数据是错误的
array([  2.12199579e-314,   6.36598737e-314,   1.06099790e-313,
         1.48539705e-313,   1.90979621e-313,   2.33419537e-313])
>>> a.dtype # 查看a的dtype
dtype('int32')
>>> b = np.fromfile("a.bin", dtype=np.int32) # 按照int32类型读入数据
>>> b # 数据是一维的
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11])
>>> b.shape = 3, 4 # 按照a的shape修改b的shape
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Note:

1. 读入的时候设置正确的dtype和shape才能保证数据一致。并且tofile函数不管数组的排列顺序是C语言格式的还是Fortran语言格式的,统一使用C语言格式输出。

2. sep关键字参数:此外如果fromfile和tofile函数调用时指定了sep关键字参数的话,数组将以文本格式输入输出。{这样就可以通过notepad++打开查看, 不过数据是一行显示,不便于查看}

user_item_mat.tofile(user_item_mat_filename, sep=' ')

转载于:https://www.cnblogs.com/pengwang52/p/9669888.html

在C语言中,我们可以创建一个函数来从.txt文件中读取数据并存储在一个数组里。这里有一个基本的例子,假设我们想要读取整数并且文件中的数据是以空格分隔的: ```c #include <stdio.h> #include <stdlib.h> // 包含malloc用于动态分配内存 // 定义数组大小,可以根据实际需要调整 #define MAX_LINES 100 #define MAX_LINE_LENGTH 100 // 函数声明 void read_file_to_array(const char* filename, int arr[], int *size); int main() { char filename[] = "example.txt"; // 文件名 int* data; // 数组指针 int size; // 调用函数并获取文件数据 read_file_to_array(filename, &data, &size); if (size > 0) { printf("Read %d numbers from file:\n", size); for (int i = 0; i < size; i++) { printf("%d ", data[i]); } printf("\n"); // 释放内存 free(data); } else { printf("Failed to read data.\n"); } return 0; } // 读取文件到数组的函数实现 void read_file_to_array(const char* filename, int arr[], int *size) { FILE* file = fopen(filename, "r"); // 打开文件 if (file == NULL) { perror("Error opening file."); *size = 0; return; } int num = 0; *size = 0; while (fgets(arr[num], MAX_LINE_LENGTH, file)) { // 逐行读取 arr[num] = strtol(arr[num], NULL, 10); // 将字符串转换为整数 if (!feof(file) && arr[num] != -1) { // 验证是否成功转换且未达到文件结束 num++; (*size)++; } else { break; // 如果出现问题则停止读取 } } arr[num] = 0; // 设置数组结尾标识 fclose(file); } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值