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中返回空响应

- 下一篇
- 如何充分发挥优秀程序员在Golang编程领域的技能
查看更多
最新文章
-
- Golang · Go问答 | 1年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 477浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何通过 client-go 和 golang 检索 Kubernetes 指标
- 486浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将多个“参数”映射到单个可变参数的习惯用法
- 439浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 将 HTTP 响应正文写入文件后出现 EOF 错误
- 357浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 结构中映射的匿名列表的“复合文字中缺少类型”
- 352浏览 收藏
-
- Golang · Go问答 | 1年前 |
- NATS Jetstream 的性能
- 101浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将复杂的字符串输入转换为mapstring?
- 440浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 相当于GoLang中Java将Object作为方法参数传递
- 212浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何确保所有 goroutine 在没有 time.Sleep 的情况下终止?
- 143浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 魔匠AI
- SEO摘要魔匠AI专注于高质量AI学术写作,已稳定运行6年。提供无限改稿、选题优化、大纲生成、多语言支持、真实参考文献、数据图表生成、查重降重等全流程服务,确保论文质量与隐私安全。适用于专科、本科、硕士学生及研究者,满足多语言学术需求。
- 20次使用
-
- PPTFake答辩PPT生成器
- PPTFake答辩PPT生成器,专为答辩准备设计,极致高效生成PPT与自述稿。智能解析内容,提供多样模板,数据可视化,贴心配套服务,灵活自主编辑,降低制作门槛,适用于各类答辩场景。
- 36次使用
-
- Lovart
- SEO摘要探索Lovart AI,这款专注于设计领域的AI智能体,通过多模态模型集成和智能任务拆解,实现全链路设计自动化。无论是品牌全案设计、广告与视频制作,还是文创内容创作,Lovart AI都能满足您的需求,提升设计效率,降低成本。
- 48次使用
-
- 美图AI抠图
- 美图AI抠图,依托CVPR 2024竞赛亚军技术,提供顶尖的图像处理解决方案。适用于证件照、商品、毛发等多场景,支持批量处理,3秒出图,零PS基础也能轻松操作,满足个人与商业需求。
- 45次使用
-
- PetGPT
- SEO摘要PetGPT 是一款基于 Python 和 PyQt 开发的智能桌面宠物程序,集成了 OpenAI 的 GPT 模型,提供上下文感知对话和主动聊天功能。用户可高度自定义宠物的外观和行为,支持插件热更新和二次开发。适用于需要陪伴和效率辅助的办公族、学生及 AI 技术爱好者。
- 45次使用
查看更多
相关文章
-
- GoLand调式动态执行代码
- 2023-01-13 502浏览
-
- 用Nginx反向代理部署go写的网站。
- 2023-01-17 502浏览
-
- Golang取得代码运行时间的问题
- 2023-02-24 501浏览
-
- 请问 go 代码如何实现在代码改动后不需要Ctrl+c,然后重新 go run *.go 文件?
- 2023-01-08 501浏览
-
- 如何从同一个 io.Reader 读取多次
- 2023-04-11 501浏览