登录
首页 >  Golang >  Go问答

Go标准库是否包含读取CSV文件并映射到字符串的功能?

来源:stackoverflow

时间:2024-03-02 15:48:29 357浏览 收藏

一分耕耘,一分收获!既然打开了这篇文章《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删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>