我想从磁盘读取一个 csv 文件到 []map[string]string 数据类型。 []slice 是行号,map["key"] 是 csv 文件的标题(第 1 行)。
我在标准库中找不到任何东西来完成这个。
最佳答案
根据回复,标准库(如 ioutil)中似乎没有任何内容可以将 csv 文件读入 map 。
给定 csv 文件路径的以下函数会将其转换为 map[string]string 的一部分。
更新:根据评论,我决定提供我的 CSVFileToMap() 和 MapToCSV() 函数,将 map 写回.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)
}
}
关于csv - Go stdlib 是否具有将 csv 文件读入 []map[string]string 的功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57102134/
我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看rubyzip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d
我试图在一个项目中使用rake,如果我把所有东西都放到Rakefile中,它会很大并且很难读取/找到东西,所以我试着将每个命名空间放在lib/rake中它自己的文件中,我添加了这个到我的rake文件的顶部:Dir['#{File.dirname(__FILE__)}/lib/rake/*.rake'].map{|f|requiref}它加载文件没问题,但没有任务。我现在只有一个.rake文件作为测试,名为“servers.rake”,它看起来像这样:namespace:serverdotask:testdoputs"test"endend所以当我运行rakeserver:testid时
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
Rails2.3可以选择随时使用RouteSet#add_configuration_file添加更多路由。是否可以在Rails3项目中做同样的事情? 最佳答案 在config/application.rb中:config.paths.config.routes在Rails3.2(也可能是Rails3.1)中,使用:config.paths["config/routes"] 关于ruby-on-rails-Rails3中的多个路由文件,我们在StackOverflow上找到一个类似的问题
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta
我正在使用ruby1.9解析以下带有MacRoman字符的csv文件#encoding:ISO-8859-1#csv_parse.csvName,main-dialogue"Marceu","Giveittohimóhe,hiswife."我做了以下解析。require'csv'input_string=File.read("../csv_parse.rb").force_encoding("ISO-8859-1").encode("UTF-8")#=>"Name,main-dialogue\r\n\"Marceu\",\"Giveittohim\x97he,hiswife.\"\