How to write data into .csv file and How to load .csv file data
github源码地址:load_data_csv/cpp
1. Python
1.Python
导入:
举例:
import pandas as pdresult0 = pd.read_csv("D:\\papers_pictures\\Debug\\result0.csv")
2. C++
2.C++
C++导出CSV文件
/cool99781/article/details/104296138
导入:
static void read_csv(const string& filename, vector<Mat>& images, vector<int>& labels, char separator = ';') {std::ifstream file(filename.c_str(), ifstream::in);if (!file) {string error_message = "No valid input file was given, please check the given filename.";CV_Error(CV_StsBadArg, error_message);}string line, path, classlabel;while (getline(file, line)) {stringstream liness(line);getline(liness, path, separator);getline(liness, classlabel);if(!path.empty() && !classlabel.empty()) {images.push_back(imread(path, 0));labels.push_back(atoi(classlabel.c_str()));}}}
注意:
atoi: string to integeratol: string to long integeratoll: string to long long integeratof: string to doubleatoff: string to float
所以只要替换成合适的数据类型即可。
导出:
#include <iostream>#include <fstream>#include <string>#include <vector>using namespace std;int main() {vector<int> images, labels;for (int i = 0; i < 100; i++){images.push_back(i);labels.push_back((i+1));}const char* addr = "E:\\5capability_practice\\cplus_learn\\csvTest\\csv_test.csv";char separator = ',';ofstream fout(addr);if (!fout.is_open()){cout<<addr<<" could not open "<<endl;return false;}fout<<"images";fout<<separator;fout<<"labels"<<endl;for (int i=0; i<(int)images.size(); i++){fout<<images[i];fout<<separator;fout<<labels[i]<<endl;}fout.close();return 0;}
3. MATLAB
注意:
**matlab无法读入除了数字以外的数据,读入进来会报错。
**csvread(path_data, 1); 里的1是从第1行开始读(从0开始算)
path_data = 'D:\papers_pictures\CR_4\Debug1\Debug\result0.csv';data = csvread(path_data, 1);
(0) What is .csv file
CSV: comma-separated values
One dimensional data per row. And each data is separated by a comma.
Make Manually a .csv file through .xlsx file:
step1: create a .xlsx file
step2: save it as .csv file
(1) Write data into .csv file
see the code detailly in main.cpp:
/*** write data into .csv file* override mode*/ const char* addr = "..\\csv_test.csv";char separator = ',';ofstream fout(addr);...fout.close();
(2) Load .csv file data
see the code detailly in main.cpp:
/*** load data from .csv file*//*** atoi: string to integer* atol: string to long integer* atoll: string to long long integer* atof: string to double* atoff: string to float*/std::string filename = "..\\results0.csv";std::ifstream file(filename.c_str(), ifstream::in);...while (getline(file, line)) {...}...file.close();
如果觉得《怎么写入数据到csv文件中以及怎么加载csv文件数据【C++ matlab Python】》对你有帮助,请点赞、收藏,并留下你的观点哦!