在golang中如何使用特定编码打开文件?

huangapple go评论73阅读模式
英文:

How to open a file with specific encoding in golang?

问题

在Go语言中,读取文件时可以使用以下方式实现类似Python中的操作:

file, err := os.Open("filepath")
if err != nil {
    // 处理错误
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    line := scanner.Text()
    // 处理每一行的内容
}

if err := scanner.Err(); err != nil {
    // 处理错误
}

在上述代码中,我们使用os.Open函数打开文件,并通过bufio.NewScanner创建一个扫描器。然后,我们可以使用scanner.Scan方法逐行读取文件内容,并通过scanner.Text获取每一行的内容进行处理。最后,我们需要检查scanner.Err是否有错误发生。记得在处理完文件后使用defer file.Close()关闭文件。

英文:

In Python, we have something like

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

How to do that in golang while reading a file?

答案1

得分: 8

在Go中,文件始终以字节级别访问,不像Python中有文本文件的概念。Go中的字符串隐式地使用UTF-8编码,因此如果您希望将文件的内容解释为UTF-8,可以简单地将从文件获取的字节转换为字符串:

package main

import (
    "fmt"
    "os"
)

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

如果您想以其他编码读取文件,您需要进行一些手动转换,例如从UTF-16到UTF-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

huangapple
  • 本文由 发表于 2022年4月2日 18:51:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/71716890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定