在GoLang中读取CSV文件,而不创建切片

hwamh0ep  于 2023-11-14  发布在  Go
关注(0)|答案(1)|浏览(80)

示例:我有一个csv文件,其中包含的值为:

Title,Name,Number,Address
Mr,Shiva,1234,Pune
Mrs,Shivai,123478,Mumbai

字符串
需要像在GoLang中一样阅读此内容,并应输出为:

Title,Name,Number,Address
Mr,Shiva,1234,Pune
Mrs,Shivai,123478,Mumbai


但是当使用GoLang内置的“encoding/csv”时,它输出为数组:

[[Title Name Number Address][Mr Shiva 1234 Pune][Mrs Shivai 123478 Mumbai]]


下面是我尝试读取CSV的代码

package main

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

func main() {
    // os.Open() opens specific file in
    // read-only mode and this return
    // a pointer of type os.File
    file, err := os.Open("CSV_FILE.csv")

    //Check if any error
    if err != nil {
        log.Fatal("Error reading CSV: ", err)
    }
    //Closes the file
    defer file.Close()

    // The csv.NewReader() function is called in
    // which the object os.File passed as its parameter
    // and this creates a new csv.Reader that reads
    // from the file
    reader := csv.NewReader(file)
    reader.Comma = ','
    // ReadAll reads all the records from the CSV file
    // and Returns them as slice of slices of string
    // and an error if any
    records, err := reader.ReadAll()

    // Checks for the error
    if err != nil {
        log.Fatal("Error reading CSV: ", err)
    }
    fmt.Println(records)
}


有人能帮忙吗?

o2gm4chl

o2gm4chl1#

而不是fmt.Println(records)调用WriteAll如下:

w := csv.NewWriter(os.Stdout)
    w.WriteAll(records) 

    if err := w.Error(); err != nil {
        log.Fatalln("error writing csv:", err)
    }

字符串
csv Example

相关问题