Golang,导入CSV并将其转换为映射。

huangapple go评论72阅读模式
英文:

Golang, importing csv and converting it to map

问题

我一直在尝试在Go中导入一个CSV文件并将其转换为map函数,但是在这方面遇到了很多困难。我遇到的问题是:

a) 即使我添加了file.Seek(0,0)以便从开头读取文件,文件仍然没有定位到开头。

b) 它没有按照期望的格式给出输出。我希望输出如下所示:

输出

map[key1:{abc 123} key2:{bcd 543} key3:{def 735}]

我的CSV文件如下:(输入)

col1   |  col2  |  col3   
key1   |   abc  |  123
key2   |   bcd  |  543
key3   |   def  |  735

由于我刚刚转向Go并且是初学者,如果您能解决我的问题,我将非常感激。

package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strings"
)

func main() {
	m := CSVFileToMap()
	fmt.Println(m)
}

func CSVFileToMap() (returnMap []map[string]string) {

	filePath := "export.csv"
	// 读取CSV文件
	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{} // 保存第一行(标题)
	for lineNum, record := range rawCSVdata {

		// 对于第一行,构建标题切片
		if lineNum == 0 {
			for i := 0; i < len(record); i++ {
				header = append(header, strings.TrimSpace(record[i]))
			}
		} else {
			// 对于每个单元格,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
}
英文:

I have been trying to import a csv file in go and convert it into map function but having a lot of difficulties in doing that. The problems that I have been facing with this code is that
a) The file not seeking to the beginning even when i have added file.Seek(0,0) so that i could read it from the beginning.
b) It is not giving me the output in desired format. I want the output to be in the as

Output

map[key1:{abc 123} key2:{bcd 543} key3:{def 735}]

My csv file is as: (Input)

<pre>
col1 | col2 | col3
key1 | abc | 123
key2 | bcd | 543
key3 | def | 735
</pre>

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 (
	&quot;encoding/csv&quot;
	&quot;fmt&quot;
	&quot;os&quot;
	&quot;strings&quot;
)

func main() {
	m := CSVFileToMap()
	fmt.Println(m)
}

func CSVFileToMap() (returnMap []map[string]string) {

	filePath := &quot;export.csv&quot;
	// 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 &lt; 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 &lt; len(record); i++ {
				line[header[i]] = record[i]
			}
			returnMap = append(returnMap, line)
		}
	}
	return returnMap
}

答案1

得分: 4

默认情况下,字段分隔符是逗号(,),你需要指定你的意图来使用竖线(|)。

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]]
英文:

By default field delimiter is , you need to specify your intent to use |

reader := csv.NewReader(csvfile)
reader.Comma = &#39;|&#39;

Output

[map[col1:key1    col2:   abc   col3:  123] map[col1:key2    col2:   bcd   col3:  543] map[col1:key3    col2:   def   col3:  735]]

huangapple
  • 本文由 发表于 2021年10月15日 13:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/69580293.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定