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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵