示例:我有一个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)
}
型
有人能帮忙吗?
1条答案
按热度按时间o2gm4chl1#
而不是
fmt.Println(records)
调用WriteAll
如下:字符串
csv Example