dongpa5277 2013-07-13 10:48
浏览 47
已采纳

将切片附加到csv golang

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..
")

    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.

  • 写回答

2条回答 默认 最新

  • duanfengtuo6012 2013-07-13 11:52
    关注

    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 (
        "encoding/csv"
        "os"
    )
    
    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) < l {
            l = len(column)
        }
        for i := 0; i < 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{"column two", "a", "b", "c", "d"}
        if err := addcol("in.csv", col); err != nil {
            panic(err)
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#单片机#的问题:以ATMEGA128或相近型号单片机为控制器设计直流电机调速的闭环控制系统(相关搜索:设计报告|软件设计|流程图)
  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办