In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
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!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.