Get the App
SLTechnology News&Howtos  ›  Development  › 

How to use Go to merge two csv

Shulou Source: shulou.com Published: 2022-06-02 22:24:35 09月17日 Update

This article mainly shows you "how to use Go to merge two csv", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use Go to merge two csv" this article.

Background

Usually we use python+pandas to deal with files, which is really fragrant. But today, someone suddenly asked me to use go to write a merge of two csv files, need to merge the two csv according to id, roughly like the following figure

The idea is simple: first read in two csv files, then traverse and compare id, and if the same, add the contents of the other file to the first. Then create the merge.csv and write the data obtained in the previous step to the csv.

Code part

Package mainimport ("encoding/csv"log"os"fmt") func join (fileName1 string, fileName2 string) (row [] [] string) {fs1, _: = os.Open (fileName1) R1: = csv.NewReader (fs1) content1, err: = r1.ReadAll () if err! = nil {log.Fatalf ("can not readall, err is% + v", err)} fs2, _: = os.Open (fileName2) R2: = csv.NewReader (fs2) content2 Err: = r2.ReadAll () if err! = nil {log.Fatalf ("can not readall, err is% + v", err)} row = make ([] [] string, len (content1 [1:]) for I, row1: = range content1 [1:] {for _, row2: = range content2 [1:] {if row1 [0] = row2 [0] {row [I] = append (row [I], row1 [0], row1 [1], row1 [2], row2 [1] Row2 [2])}} return} func edit (filename string, row [] [] string) {f, err: = os.Create (filename) if err! = nil {panic (err)} defer f.Close () / / prevent garbled f.WriteString ("\ xEF\ xBB\ xBF") w: = csv.NewWriter (f) w.Write ([] string {"ID", "name", "gender", "course") "score"}) w.WriteAll (row) w.Flush ()} func main () {row: = join ("1.csv", "2.csv") fmt.Println (row) edit ("join.csv", row) fmt.Println ("merge completed!") }

The above is all the content of the article "how to use Go to merge two csv". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Two content documents articles learning help same garbled code ideas data easy to understand more organization knowledge editing background industry information information channels Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei Docker Shulou Tech Info OPPO Reno Shulou Information