将切片追加到CSV文件中,使用Golang。

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

append slice to csv golang

问题

我试图创建一个简单的函数,将一个切片值附加到创建的csv文件的下一列。目标是在test.csv中实现以下样式:

|columnA |columnB|

|header1 |header2|

|FIRSTVALUE| SECONDVALUE |

(对于格式不好的问题,但是一旦生成了text.csv文件,如果我们打开text.csv文件,想法是在“FIRSTVALUE”之后将“SECONDVALUE”放在下一列(如上图所示)...每次调用函数时,它将在同一行的前一列后追加下一个值)。

这是我目前的进展,但它直接将SECONDVALUE附加到FIRSTVALUE的同一列中...(所以我得到的是“|FIRSTVALUESECONDVALUE|”,而不是“|FIRSTVALUE | SECONDVALUE”)

如何修复上面的代码行,使“SECONDVALUE”成为第二列,而不是与“FIRSTVALUE”相同的列。

英文:

I tried to create a simple function to append a slice value to the next column of a created csv file. The aim is to have this style in test.csv

|columnA |columnB|

|header1 |header2|

|FIRSTVALUE| SECONDVALUE |

(sorry for the bad formating, but once the text.csv is generated, if we open the text.csv file,the idea is to have the "SECONDVALUE" put in the next column after the "FIRSTVALUE" (as is depicted in the diagram above).. and everytime the function is called, it will keep appending the next value after the previous column in the same line).

This is how far I got, it is however appending the SECONDVALUE directly on the same column of FIRSTVALUE.. (so instead of getting "|FIRSTVALUE | SECONDVALUE" , I get "|FIRSTVALUESECONDVALUE|" )

package main

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


func main() {
	callfunc()
}

func callfunc() int {

	testval1 := []string{"FIRST VALUE"}
	test(testval1, "test.csv", 1)

	testval2 := []string{"SECOND VALUE"}
	test(testval2, "test.csv", 0) //I want this to be added to the column next to first value 

	return 1
}


func test(lines []string, path string, header int) {

	var hdr = []string{"header1", "header2"}

	fmt.Println("inside the method..\n")

	file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600)
	if err != nil {
		if file, err = os.Create(path); err != nil {
			return
		}
	}
	defer file.Close()

	writer := csv.NewWriter(file)

	if header == 1 {
		returnError := writer.Write(hdr)
		if returnError != nil {
			fmt.Println(returnError)
		}
	}

	writer.Flush()

	for _, value := range lines {
		_, err := file.WriteString(strings.TrimSpace(value))
		if err != nil { //exception handler
			fmt.Println(err)
			break
		}
	}

	writer.Flush()
}

how to fix the above line of code , so that "SECONDVALUE" is the second column, and not in the same column where the "FIRSTVALUE" is.

答案1

得分: 7

func addcol(fname string, column []string) {
// 读取文件
f, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
if err != nil {
fmt.Println("错误: ", err)
return
}
w := csv.NewWriter(f)
w.Write(column)
w.Flush()
}

英文:
func addcol(fname string, column []string)  {
 // read the file
 f, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
 if err != nil {
	 fmt.Println("Error: ", err)
	 return
 }
 w := csv.NewWriter(f)
 w.Write(column)
 w.Flush()
}

copy from https://www.reddit.com/r/golang/comments/46fdef/help_appending_a_slice_to_next_row_in_csv_file/

答案2

得分: 4

package main

import (
"encoding/csv"
"os"
)

func addcol(fname string, column []string) error {
// 读取文件
f, err := os.Open(fname)
if err != nil {
return err
}
r := csv.NewReader(f)
lines, err := r.ReadAll()
if err != nil {
return err
}
if err = f.Close(); err != nil {
return err
}

// 添加列
l := len(lines)
if len(column) < l {
	l = len(column)
}
for i := 0; i < l; i++ {
	lines[i] = append(lines[i], column[i])
}

// 写入文件
f, err = os.Create(fname)
if err != nil {
	return err
}
w := csv.NewWriter(f)
if err = w.WriteAll(lines); err != nil {
	f.Close()
	return err
}
return f.Close()

}

func main() {
col := []string{"column two", "a", "b", "c", "d"}
if err := addcol("in.csv", col); err != nil {
panic(err)
}
}

英文:

Your code includes things which I couldn’t understand clearly, so here’s a tiny program that does what your are asking for. You can build on top of it.

package main

import (
	&quot;encoding/csv&quot;
	&quot;os&quot;
)

func addcol(fname string, column []string) error {
	// read the file
	f, err := os.Open(fname)
	if err != nil {
		return err
	}
	r := csv.NewReader(f)
	lines, err := r.ReadAll()
	if err != nil {
		return err
	}
	if err = f.Close(); err != nil {
		return err
	}

	// add column
	l := len(lines)
	if len(column) &lt; l {
		l = len(column)
	}
	for i := 0; i &lt; l; i++ {
		lines[i] = append(lines[i], column[i])
	}

	// write the file
	f, err = os.Create(fname)
	if err != nil {
		return err
	}
	w := csv.NewWriter(f)
	if err = w.WriteAll(lines); err != nil {
		f.Close()
		return err
	}
	return f.Close()
}

func main() {
	col := []string{&quot;column two&quot;, &quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;}
	if err := addcol(&quot;in.csv&quot;, col); err != nil {
		panic(err)
	}
}

huangapple
  • 本文由 发表于 2013年7月13日 18:48:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/17629451.html
匿名

发表评论

匿名网友

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

确定