GoThe language comesCSVThe file reading module looks good. Playing with it today is part of the system's learning of the Go language ...... Pai_^
I. WriteCSVFile
Function:
Func
Newwriter (W Io. Writer) * Writer
Func
(W * writer) flush ()
Func
(W * writer) write (record [] string) (err OS. Error)
Func
(W * writer) writeall (records [] [] string) (err OS. Error)
For details, see the official website:Http://golang.org/pkg/csv/#NewWriter
Actually writeCSVYou do not need to use these functions to write files directly according to the rules. However, you still need to write these functions here.DemoTo facilitate future use:
PackageMain Import( "CSV" "OS" "Bytes" "FMT" ) FuncMain (){ Filename: ="2.csv" Buf: =New(Bytes. Buffer) R2: = CSV. newwriter (BUF) for I: = 0 ; I 10 ; I ++ { S: = make ([] string , 3 ) S [0] ="User ID" S [1] ="Name" S [2] ="Depart" R2.write (s) R2.flush () } FMT. println (BUF) Fout, err: = OS. Create (filename) DeferFout. Close () IfErr! =Nil{ FMT. println (filename, err) Return } Fout. writestring (BUF. String ()) }
Ii. ReadCSVFile
Function:
Func
Newreader (r Io. Reader) * Reader
Func
(R * reader) read () (record [] string, err OS. Error)
Func
(R * reader) readall () (records [] [] string, err OS. Error)
For details, see the official website:Http://golang.org/pkg/csv/#Reader.Read
1The first thing to solve is to read all the content of the file and coexist as a string. Here we useIoutilModule, detailsCodeAs follows:
PackageMain Import( "IO/ioutil" "FMT" ) FuncMain (){ B, err: = ioutil. readfile ("1.csv") IfErr! =Nil{ Panic(ERR. String ()) } // FMT. println (B) FMT. printf ("% S",String(B )) }
2, ReadCSVFile Content:
PackageMain Import( "FMT" "CSV" "Strings" "IO/ioutil" ) FuncMain (){ // Filename: = "1.csv" FMT. printf ("Input file name :") VaRFilenameString FMT. scanf ("% S", & Filename) Cntb, err: = ioutil. readfile (filename) IfErr! =Nil{ Panic(ERR. String ()) } R2: = CSV. newreader (strings. newreader (String(Cntb ))) SS, _: = r2.readall () // FMT. println (SS) SZ: =Len(Ss) ForI: =0; I <SZ; I ++ { FMT. println (ss [I]) } }
well, that's all. Hope to help you