Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang readline and writeline
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
@thorbenvh8

This comment has been minimized.

Copy link

@thorbenvh8 thorbenvh8 commented Mar 28, 2018

replace

fmt.Fprintln(w, line)

with

writer.WriteString(line)
@logrusorgru

This comment has been minimized.

Copy link

@logrusorgru logrusorgru commented Aug 14, 2018

TheFprintln adds \n or \r\n depending on OS. But the WriteString doesn't.

var nl = fmt.Sprintln() // new line, depending on OS

// [...]

w.WriteString(line)
w.WriteString(nl)
@logrusorgru

This comment has been minimized.

Copy link

@logrusorgru logrusorgru commented Aug 15, 2018

Hah. It seems Go every time uses \n. Interesting.
Thus,

w.WriteString(line)
w.WrieByte('\n')
@alisher-matkurbanov

This comment has been minimized.

Copy link

@alisher-matkurbanov alisher-matkurbanov commented Oct 14, 2020

why you don't handle err from fmt.Fprintln(w, line)?
wouldn't it be better to write like this

...
for _, line := range lines {
    _, err = fmt.Fprintln(w, line)
    if err != nil {
        return err
    }
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment