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

如何将CSV文件内容存入二维vector以适配ESP32运行需求

实现方法

完全可以将CSV内容直接嵌入代码中,无需读取外部存储文件,具体实现如下:

核心思路

将CSV文件的全部内容直接定义为代码中的多行字符串常量,直接解析该字符串得到二维数据,完全跳过文件读取步骤。

适配ESP32 MicroPython的实现代码

首先把你的A00068.csv文件内容全部复制,替换下面代码中CSV_CONTENT的字符串内容即可:

# 直接把CSV内容写为多行字符串常量
CSV_CONTENT = """1.2,3.4,5.6
7.8,9.1,2.3
4.5,6.7,8.9"""

def read_csv_content():
    csv_data = []
    # 按行拆分字符串
    for line in CSV_CONTENT.splitlines():
        # 跳过空行
        if not line.strip():
            continue
        # 按逗号拆分转浮点数
        row = [float(item) for item in line.split(',')]
        csv_data.append(row)
    return csv_data

# 调用测试
csv_data = read_csv_content()
print("SIZE:", len(csv_data))
# 打印全部内容
for i, row in enumerate(csv_data):
    print(f"行{i}: {row}")

如果你仍需使用C++版本(适配ESP-IDF环境)

可以直接修改原来的读取函数,传入字符串内容而非文件名,代码如下:

#include <vector>
#include <string>
#include <sstream>

// 直接定义CSV内容常量,把你CSV的内容替换进去即可
const char* CSV_CONTENT = R"(1.2,3.4,5.6
7.8,9.1,2.3
4.5,6.7,8.9)";

std::vector<std::vector<double>> read_csv_from_str(const char* content)
{
    std::vector<std::vector<double>> csv_data;
    std::stringstream content_ss(content);
    std::string lineStr;
    while (getline(content_ss, lineStr))
    {
        if (lineStr.empty()) continue;
        std::stringstream ss(lineStr);
        std::string d;
        std::vector<double> a_line_data;
        while (getline(ss, d, ','))
        {
            a_line_data.push_back(atof(d.c_str()));
        }
        csv_data.push_back(a_line_data);
    }
    return csv_data;
}

// 调用测试代码
void test() {
    std::vector<std::vector<double>> csv_data = read_csv_from_str(CSV_CONTENT);
    printf("SIZE:%d\n", csv_data.size());
    // 打印内容,注意不能直接用printf打印vector,需要循环遍历
    for (int i = 0; i < csv_data.size(); i++) {
        printf("行%d: ", i);
        for (int j = 0; j < csv_data[i].size(); j++) {
            printf("%.2f ", csv_data[i][j]);
        }
        printf("\n");
    }
}

注意事项

  • 若CSV数据量较大,需确认不超过ESP32的可用Flash容量
  • MicroPython中字符串常量默认存储在Flash中,不会占用运行内存,无需额外优化

内容的提问来源于stack exchange,提问作者Vaibhav Vishwakarma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 22:27:05