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年前 |
- 在读取缓冲通道中的内容之前退出
- 139浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 戈兰岛的全球 GOPRIVATE 设置
- 204浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何将结构作为参数传递给 xml-rpc
- 325浏览 收藏
-
- Golang · Go问答 | 1年前 |
- 如何用golang获得小数点以下两位长度?
- 478浏览 收藏
-
- 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基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3203次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3416次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3446次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4554次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3824次使用
查看更多
相关文章
-
- 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浏览

