我一直在尝试在 go 中导入 csv 文件并将其转换为 map 函数,但在这方面遇到了很多困难。我在使用这段代码时遇到的问题是
a)即使我添加了file.Seek(0,0)
,文件也不寻找开头这样我就可以从头开始阅读。
b)它没有给我所需格式的输出。我希望输出位于 as 中
输出
map[key1:{abc 123} key2:{bcd 543} key3:{def 735}]
我的 csv 文件如下:(输入)
col1 | col2 | col3 key1 | abc | 123 key2 | bcd | 543 key3 | def | 735
As I have just switched to go and is a beginner, It would be very kind of you if you solve my issue.
package main
import (
"encoding/csv"
"fmt"
"os"
"strings"
)
func main() {
m := CSVFileToMap()
fmt.Println(m)
}
func CSVFileToMap() (returnMap []map[string]string) {
filePath := "export.csv"
// read csv file
csvfile, err := os.Open(filePath)
if err != nil {
return nil
}
defer csvfile.Close()
csvfile.Seek(0, 0)
reader := csv.NewReader(csvfile)
rawCSVdata, err := reader.ReadAll()
if err != nil {
return nil
}
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 returnMap
}
最佳答案
默认字段分隔符是,
您需要指定使用|
的意图
reader := csv.NewReader(csvfile)
reader.Comma = '|'
输出
[map[col1:key1 col2: abc col3: 123] map[col1:key2 col2: bcd col3: 543] map[col1:key3 col2: def col3: 735]]
关于Golang,导入csv并将其转换为 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69580293/