package main import ( "bufio" "encoding/csv" "fmt" "io" "os" "strings" ) func main() { f, err := os.Open("new.txt") if err != nil { panic(err) } defer f.Close() rd := bufio.NewReader(f) f2, err2 := os.Create("data.csv") if err2 != nil { panic(err2) } defer f2.Close() //f2.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM w := csv.NewWriter(f2) var header = []string{"Time", "cpu"} w.Write(header) for { line, err := rd.ReadString('\n') //以'\n'为结束符读入一行 if err != nil || io.EOF == err { break } s := strings.Split(strings.TrimSpace(line), " ") fmt.Println(s[1], s[2]) w.Write([]string{s[1], s[2]}) } // 将缓存中的内容写入到文件里 w.Flush() }