golang語言實現讀取csv檔案內容,把相同的內容提取到另外一個檔案

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
package mainimport ("encoding/csv""fmt""io""os""path/filepath""strconv")func CheckErr(err error) {if nil != err {panic(err)}}func GetFullPath(path string) string {absolutePath, _ := filepath.Abs(path)return absolutePath}func WriteFile(content []string) {f, err := os.OpenFile("sameName.csv", os.O_APPEND|os.O_CREATE, os.ModeAppend)CheckErr(err)defer f.Close()f.WriteString("\xEF\xBB\xBF")writer := csv.NewWriter(f)writer.Write(content)writer.Flush()}var exsit []string = []string{}func Exsit(name string) bool {size := len(exsit)for i := 0; i < size; i++ {if exsit[i] == name {return true}}return false}func findSame(path string) {fullPath := GetFullPath(path)records := getStrings(fullPath)size := len(records)for i := 0; i < size; i++ {rec := records[i]recNoDate := rec[:len(rec)-19]flag := 1for i2 := i + 1; i2 < size; i2++ {if recNoDate == records[i2][:len(records[i2])-19] && !Exsit(recNoDate) {WriteFile([]string{strconv.Itoa(flag), records[i2]})flag++}}if flag > 1 && !Exsit(recNoDate) {exsit = append(exsit, recNoDate)WriteFile([]string{strconv.Itoa(flag), rec})}}size = len(exsit)f, err := os.OpenFile("debug.csv", os.O_APPEND|os.O_CREATE, os.ModeAppend)CheckErr(err)defer f.Close()f.WriteString("\xEF\xBB\xBF")writer := csv.NewWriter(f)for i := 0; i < size; i++ {writer.Write([]string{exsit[i]})}writer.Flush()}func getStrings(path string) []string {f, err := os.Open(path)CheckErr(err)defer f.Close()records := []string{}reader := csv.NewReader(f)record := []string{}for {record, err = reader.Read()if err == io.EOF {break} else if nil != err {fmt.Println(err)return nil}records = append(records, record[0])}return records}func main() {var path stringif len(os.Args) > 1 {path = os.Args[1]} else {path, _ = os.Getwd()}findSame(path)fmt.Println("done!")}


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.