go 修改csv文件案例,读取文件内容,缓存修改后再覆盖写入
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
)
func main() {
WriteCsv()
//ReadCsv()
ModifyCsv()
multiRoutineWriteCsv()
}
func WriteCsv() {
f, _ := os.Create("test.csv")
defer f.Close()
f.WriteString("\xEF\xBB\xBF") //写入utf-8 编码
w := csv.NewWriter(f)
w.Write([]string{"网站", "类型"})
w.Write([]string{"知乎", "问答类"})
w.Write([]string{"百度", "搜索类"})
w.Write([]string{"B站", "视频类"})
w.Flush()
}
func ReadCsv() {
f, _ := os.Open("test.csv")
reader := csv.NewReader(f)
//reader.Comma = ';'
defer f.Close()
count := 0
var record []string
var err error
for {
record, err = reader.Read()
if err != nil {
if err == io.EOF {
err = nil
}
break
}
count++
fmt.Printf("%#v \n", record)
}
/*f2, _ := os.Open("test.csv")
reader2 := csv.NewReader(f2)
record2, _ := reader2.ReadAll()
fmt.Println(record2)
f2.Close()*/
}
func ModifyCsv() {
f, _ := os.Open("test.csv")
//defer f.Close()
reader := csv.NewReader(f)
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
f.Close()
fmt.Println(records)
for i := 0; i < len(records); i++ {
for j := 0; j < len(records[0]); j++ {
records[i][j] = records[i][j] + "1"
}
}
//修改二维数组,然后再重新写入,达到修改的目的
file, err := os.Create("test.csv")
defer file.Close()
//file.WriteString("\xEF\xBB\xBF") //写入utf-8 编码
w := csv.NewWriter(file)
/*w.Write([]string{"百度1", "搜索类1"})
w.Write([]string{"B站1", "视频类1"})*/
w.WriteAll(records)
w.Flush()
}
func multiRoutineWriteCsv() {
wg := sync.WaitGroup{}
f, _ := os.Create("multiGoRoutineTest1.csv")
defer f.Close()
f.WriteString("\xEF\xBB\xBF") //写入utf-8 编码
w := csv.NewWriter(f)
syncMap := sync.Map{}
for i := 0; i < 20; i++ {
wg.Add(1)
go func(i int, wg *sync.WaitGroup, w *csv.Writer) {
defer wg.Done()
syncMap.Store("问答类"+strconv.Itoa(i), i)
syncMap.Store("类型"+strconv.Itoa(i), i)
syncMap.Store("知乎"+strconv.Itoa(i), i)
syncMap.Store("百度"+strconv.Itoa(i), i)
syncMap.Store("B站"+strconv.Itoa(i), i)
syncMap.Store("视频类"+strconv.Itoa(i), i)
}(i, &wg, w)
}
wg.Wait()
syncMap.Range(func(key, value interface{}) bool {
strings := key.(string)
w.Write([]string{strings})
return true
})
w.Flush()
}
Go二维数组的排序案例
func Test2Array(t *testing.T) {
interval := [][]string{
{strconv.Itoa(rand.Intn(100)), strconv.Itoa(rand.Intn(100))},
{strconv.Itoa(rand.Intn(100)), strconv.Itoa(rand.Intn(100))},
{strconv.Itoa(rand.Intn(100)), strconv.Itoa(rand.Intn(100))},
{strconv.Itoa(rand.Intn(100)), strconv.Itoa(rand.Intn(100))},
}
fmt.Println(interval)
sort.Slice(interval, func(i, j int) bool {
if interval[i][0] == interval[j][0] {
return interval[i][1] < interval[j][1]
} else {
return interval[i][0] < interval[j][0]
}
})
fmt.Println(interval)
}
执行结果:
[[81 87] [47 59] [81 18] [25 40]]
[[25 40] [47 59] [81 18] [81 87]]