Go标准库是否包含读取CSV文件并映射到字符串的功能?
来源:stackoverflow
2024-03-02 15:48:29
0浏览
收藏
一分耕耘,一分收获!既然打开了这篇文章《Go标准库是否包含读取CSV文件并映射到字符串的功能?》,就坚持看下去吧!文中内容包含等等知识点...希望你能在阅读本文后,能真真实实学到知识或者帮你解决心中的疑惑,也欢迎大佬或者新人朋友们多留言评论,多给建议!谢谢!
问题内容
我想将 csv 文件从磁盘读取为 []map[string]string 数据类型。其中 []slice 是行号,map["key"] 是 csv 文件的标题(第 1 行)。
我在标准库中找不到任何东西来完成这个任务。
解决方案
根据回复,听起来标准库中没有任何内容(例如 ioutil)可以将 csv 文件读入地图。
给定 csv 文件路径的以下函数会将其转换为 map[string]string 的切片。
更新:根据评论,我决定提供 csvfiletomap() 和 maptocsv() 函数,将地图写回csv 文件。
package main
import (
"os"
"encoding/csv"
"fmt"
"strings"
)
// csvfiletomap reads csv file into slice of map
// slice is the line number
// map[string]string where key is column name
func csvfiletomap(filepath string) (returnmap []map[string]string, err error) {
// read csv file
csvfile, err := os.open(filepath)
if err != nil {
return nil, fmt.errorf(err.error())
}
defer csvfile.close()
reader := csv.newreader(csvfile)
rawcsvdata, err := reader.readall()
if err != nil {
return nil, fmt.errorf(err.error())
}
header := []string{} // holds first row (header)
for linenum, record := range rawcsvdata {
// for first row, build the header slice
if linenum == 0 {
for i := 0; i < len(record); i++ {
header = append(header, strings.trimspace(record[i]))
}
} else {
// for each cell, map[string]string k=header v=value
line := map[string]string{}
for i := 0; i < len(record); i++ {
line[header[i]] = record[i]
}
returnmap = append(returnmap, line)
}
}
return
}
// maptocsvfile writes slice of map into csv file
// filterfields filters to only the fields in the slice, and maintains order when writing to file
func maptocsvfile(inputslicemap []map[string]string, filepath string, filterfields []string) (err error) {
var headers []string // slice of each header field
var line []string // slice of each line field
var csvline string // string of line converted to csv
var csvcontent string // final output of csv containing header and lines
// iter over slice to get all possible keys (csv header) in the maps
// using empty map[string]struct{} to get unique keys; no value needed
var headermap = make(map[string]struct{})
for _, record := range inputslicemap {
for k, _ := range record {
headermap[k] = struct{}{}
}
}
// convert unique headersmap to slice
for headervalue, _ := range headermap {
headers = append(headers, headervalue)
}
// filter to filteredfields and maintain order
var filteredheaders []string
if len(filterfields) > 0 {
for _, filterfield := range filterfields {
for _, headervalue := range headers {
if filterfield == headervalue {
filteredheaders = append(filteredheaders, headervalue)
}
}
}
} else {
filteredheaders = append(filteredheaders, headers...)
sort.strings(filteredheaders) // alpha sort headers
}
// write headers as the first line
csvline, _ = writeascsv(filteredheaders)
csvcontent += csvline + "\n"
// iter over inputslicemap to get values for each map
// maintain order provided in header slice
// write to csv
for _, record := range inputslicemap {
line = []string{}
// lines
for k, _ := range filteredheaders {
line = append(line, record[filteredheaders[k]])
}
csvline, _ = writeascsv(line)
csvcontent += csvline + "\n"
}
// make the dir incase it's not there
err = os.mkdirall(filepath.dir(filepath), os.modeperm)
if err != nil {
return err
}
// write out the csv contents to file
ioutil.writefile(filepath, []byte(csvcontent), os.filemode(0644))
if err != nil {
return err
}
return
}
func writeascsv(vals []string) (string, error) {
b := &bytes.buffer{}
w := csv.newwriter(b)
err := w.write(vals)
if err != nil {
return "", err
}
w.flush()
return strings.trimsuffix(b.string(), "\n"), nil
}
最后,这是一个测试用例来展示它的用法:
func TestMapToCSVFile(t *testing.T) {
// note: test case requires the file ExistingCSVFile exist on disk with a
// few rows of csv data
SomeKey := "some_column"
ValueForKey := "some_value"
OutputCSVFile := `.\someFile.csv`
ExistingCSVFile := `.\someExistingFile.csv`
// read csv file
InputCSVSliceMap, err := CSVFileToMap(ExistingCSVFile)
if err != nil {
t.Fatalf("MapToCSVFile() failed %v", err)
}
// add a field in the middle of csv
InputCSVSliceMap[2][SomeKey] = ValueForKey // add a new column name
"some_key" with a value of "some_value" to the second line.
err = MapToCSVFile(InputCSVSliceMap, OutputReport, nil)
if err != nil {
t.Fatalf("MapToCSVFile() failed writing outputReport %v", err)
}
// VALIDATION: check that Key field is present in MapToCSVFile output file
// read Output csv file
OutputCSVSliceMap, err := CSVFileToMap(OutputCSVFile)
if err != nil {
t.Fatalf("MapToCSVFile() failed reading output file %v", err)
}
// check that the added key has a value for Key
if OutputCSVSliceMap[2][SomeKey] != ValueForKey {
t.Fatalf("MapToCSVFile() expected row to contains key value: %v", ValueForKey)
}
}今天关于《Go标准库是否包含读取CSV文件并映射到字符串的功能?》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!
版本声明
本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
Go HTTP服务器在Docker中返回空响应
- 上一篇
- Go HTTP服务器在Docker中返回空响应
- 下一篇
- 如何充分发挥优秀程序员在Golang编程领域的技能
查看更多
最新文章
-
- Golang · Go问答 | 1分钟前 | go · 问题排查 · Go tview tview焦点 InputField Flex AddItem Application SetFocus
- Go tview 新增输入组件后为什么键盘焦点没切换
- 304浏览 收藏
-
- Golang · Go问答 | 6分钟前 | go · 问题排查 · Go tcell tcell PollEvent EventInterrupt PostEvent 终端事件退出
- Go tcell 退出信号到来时怎么结束阻塞的事件读取
- 178浏览 收藏
-
- Golang · Go问答 | 10分钟前 | go · 问题排查 · Go tcell tcell窗口缩小 EventResize Screen.Sync 终端重绘
- Go tcell 窗口缩小后旧字符残留怎么办
- 316浏览 收藏
-
- Golang · Go问答 | 12分钟前 |
- Go tcell Show 和 Sync 重绘有什么区别
- 168浏览 收藏
-
- Golang · Go问答 | 18分钟前 | 错误处理 · go · 校验 · 表单 · 表单校验 Go问答 Bubble Tea Go huh huh.ErrUserAborted
- Go huh 用户取消表单后怎么区分取消与校验失败
- 377浏览 收藏
-
- Golang · Go问答 | 21分钟前 |
- Go huh 依赖前一字段的选项为什么没有刷新
- 367浏览 收藏
-
- Golang · Go问答 | 30分钟前 |
- Go Lip Gloss Width 和 MaxWidth 在文本换行时有什么区别
- 429浏览 收藏
-
- Golang · Go问答 | 31分钟前 | go ·
- Go Lip Gloss 颜色效果在不同终端不一致怎么办
- 228浏览 收藏
-
- Golang · Go问答 | 31分钟前 | Go问答 · ANSI len Go Lip Gloss 终端单元格宽度 lipgloss.Width lipgloss.Size
- Go Lip Gloss 带颜色字符串为什么不能用 len 判断显示宽度
- 418浏览 收藏
-
- Golang · Go问答 | 46分钟前 |
- Go Bubble Tea Batch 与顺序执行命令有什么区别
- 119浏览 收藏
-
- Golang · Go问答 | 46分钟前 |
- Go Bubble Tea 定时消息为什么触发一次就停止
- 251浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 459次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 521次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 536次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 486次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 306次使用
查看更多
相关文章
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- Go crypto/rand.Text 的长度为什么不是固定字符数
- 2026-10-04 501浏览
-
- Go strings.ToValidUTF8 清洗日志内容的边界
- 2026-10-03 501浏览
-
- Go tls.GetCertificate 为什么收不到空 ServerName 请求
- 2026-09-27 501浏览

