This is a creation in Article, where the information may have evolved or changed.
Http://stackoverflow.com/questions/5884154/golang-read-text-file-into-string-array-and-write
Method One
1 Package Main2 3 Import (4 "Bufio"5 "FMT"6 "Log"7 "OS"8 )9 Ten //ReadLines reads a whole file into memory One //And returns a slice of its lines. AFunc ReadLines (pathstring) ([]string, error) { -File, err: =OS. Open (PATH) - ifErr! =Nil { the returnNil, err - } - defer file. Close () - + varLines []string -Scanner: =Bufio. Newscanner (file) + forscanner. Scan () { ALines =Append (lines, scanner. Text ()) at } - returnlines, scanner. ERR () - } - - //Writelines writes the lines to the given file. -Func writelines (lines []string, Pathstring) Error { inFile, err: =OS. Create (PATH) - ifErr! =Nil { to returnErr + } - defer file. Close () the *W: =Bufio. Newwriter (file) $ for_, Line: =Range Lines {Panax Notoginseng FMT. Fprintln (W, line) - } the +}
Method Two (relatively concise, but the file can not be too large)
1 content, err: = ioutil. ReadFile (filename)2if err! = Nil {3 //dosomething 4}5 lines: = Strings. Split (string"\ n")