Skip to content

Instantly share code, notes, and snippets.

@yogesh-desai
Forked from wofeiwo/readLines-writeLines.go
Created October 19, 2016 15:56
Show Gist options
  • Save yogesh-desai/219440bacf4dba0fbf17d2aacbbe997b to your computer and use it in GitHub Desktop.
Save yogesh-desai/219440bacf4dba0fbf17d2aacbbe997b to your computer and use it in GitHub Desktop.
read lines write lines like python api in golang
package main
import (
"io"
"os"
"bufio"
"bytes"
"fmt"
"strings"
)
func readLines(path string)(lines [] string,err error){
var (
file *os.File
part [] byte
prefix bool
)
if file, err = os.Open(path); err != nil {
return
}
reader := bufio.NewReader(file)
buffer := bytes.NewBuffer(make([]byte,1024))
for {
if part, prefix, err = reader.ReadLine();err != nil {
break
}
buffer.Write(part)
if !prefix {
lines = append(lines,buffer.String())
buffer.Reset()
}
}
if err == io.EOF {
err = nil
}
return
}
func writeLines(lines [] string,path string)(err error){
var file *os.File
if file,err = os.Create(path); err != nil{
return
}
defer file.Close()
for _,elem := range lines {
_,err := file.WriteString(strings.TrimSpace(elem)+"\n")
if err != nil {
fmt.Println(err)
break
}
}
return
}
func main(){
lines, err := readLines("5906376")
if err != nil{
fmt.Println("Error:%s\n",err)
return
}
for _,line := range lines {
fmt.Println(line)
}
err= writeLines(lines,"a.txt")
fmt.Println(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment