1

In Python, we have something like

open("filepath", encoding="utf8")

How to do that in golang while reading a file?

JY F
  • 39
  • 1
  • 6
  • Files are collections of bytes. Go `string` supports UTF8 - that can also store sequences of bytes that may or may not be valid UTF8. To check if a read sequence of bytes is valid use [unicode.utf8](https://pkg.go.dev/unicode/utf8#Valid) – colm.anseo Apr 02 '22 at 11:09

1 Answers1

8

In Go files are always accessed on a byte level, unlike python which has the notion of text files. Strings in go are implicitly UTF-8 so you can simply convert the bytes gotten from a file to a string if you want to interpret the contents as UTF-8:

package main

import (
    "fmt"
    "os"
)

func main() {
    dat, err := os.ReadFile("/tmp/dat")
    if err != nil {
        panic(err)
    }
    fmt.Print(string(dat))
}

If you want to read files in any other encoding you will need to do some manual conversion, UTF-16 to UTF-8 for example

Dylan Reimerink
  • 5,874
  • 2
  • 15
  • 21