C++
//读csv文件
bool ReadCsvFile(const std::string &csv_file, std::vector<std::vector<std::string>> &output) {
try {
std::cout << "csv_file:" << csv_file << std::endl;
std::ifstream f;
f.open(csv_file, std::fstream::in);
if (!f.is_open()) {
std::cout << "ReadCsvFile is false! csv_file = " << csv_file << std::endl;
return false;
}
std::string line;
while (getline(f, line)) {
std::vector<std::string> data;
boost::split(data, line, boost::is_any_of(","), boost::token_compress_on);
output.push_back(data);
}
f.close();
} catch (std::exception &e) {
std::cout << "ReadCsvFile is false! e = " << e.what() << std::endl;
return false;
}
std::cout << "ReadCsvFile is success!" << std::endl;
return true;
}
//初始化带中文的csv
bool InitChineseCsv(std::string csv_file, std::string title) {
try {
char szUTF_8BOM[4] = {char(0xEF), char(0xBB), char(0xBF), char(0)};
std::ofstream f(csv_file, ios::out);
if (!f.is_open()) {
std::cout << "InitChineseCsv is false! csv_file:" << csv_file << std::endl;
return false;
}
f << szUTF_8BOM << title;
f.close();
} catch (std::exception &e) {
std::cout << "InitChineseCsv is false! e = " << e.what() << std::endl;
return false;
}
return true;
}
// 写csv
bool WriteVectorToCsv(const std::vector<std::vector<std::string>> &lines, std::string output_file) {
try {
std::ofstream out_f(output_file, std::ios::app);
if (!out_f.is_open()) {
std::cout << "WriteVectorToCsv is false! output_file:" << output_file << std::endl;
return false;
}
for (auto line : lines) {
for (int i = 0; i < line.size(); i++) {
// 去除line中的","
std::string data = line[i];
string::size_type pos = data.find(",");
while (pos != string::npos) {
data.replace(pos, 1, " ");
pos = data.find(",");
}
if (i != line.size() - 1) {
out_f << data << ",";
} else {
out_f << data << std::endl;
}
}
}
out_f.close();
} catch (std::exception &e) {
std::cout << "WriteVectorToCsv is false! e = " << e.what() << std::endl;
return false;
}
std::cout << "WriteVectorToCsv is success!" << std::endl;
return true;
}
python
# 读csv
def read_form_csv(csv_file):
with open(csv_file, "r") as s_f:
lines_temp = s_f.readlines()
lines = []
for line in lines_temp:
# 防止有silly boy写,到csv中
line = line.strip().split(",")
lines.append(line)
return lines
# 添加中文头文件
def add_bom_for_windows(file):
with open(file, "wb") as f:
f.write(codecs.BOM_UTF8)
# 写csv
def write_csv_from_list(input_list, csv_file):
try:
add_bom_for_windows(csv_file)
with open(csv_file, "a", encoding="utf-8-sig") as f:
csv_write = csv.writer(f)
csv_write.writerows(input_list)
except Exception as e:
print("write_csv_from_list is false! csv_file = {} , e = {}".format(
csv_file, e))
return False
return True