-
-
Save yogesh-desai/219440bacf4dba0fbf17d2aacbbe997b to your computer and use it in GitHub Desktop.
read lines write lines like python api in golang
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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