如何阅读文本文件? [英] How to read a text file?
问题描述
我正在尝试读取"file.txt",然后使用Golang将内容放入变量中.这是我尝试过的...
I'm trying to read "file.txt" and put the contents into a variable using Golang. Here is what I've tried...
package main
import (
"fmt"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
fmt.Print(file)
}
文件已成功读取,并且从 os.Open 返回的返回类型为 * os.File
The file gets read successfully and the return from os.Open returns a type of *os.File
推荐答案
这取决于您要执行的操作.
It depends on what you are trying to do.
file, err := os.Open("file.txt")
fmt.print(file)
之所以输出& {0xc082016240},是因为您正在打印文件描述符( * os.File
)的指针值,而不是文件内容.要获取文件内容,可以从文件描述符中 READ
.
The reason it outputs &{0xc082016240}, is because you are printing the pointer value of a file-descriptor (*os.File
), not file-content. To obtain file-content, you may READ
from a file-descriptor.
要读取所有文件内容(以字节为单位)到内存,请 ioutil.ReadAll
To read all file content(in bytes) to memory, ioutil.ReadAll
package main
import (
"fmt"
"io/ioutil"
"os"
"log"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
b, err := ioutil.ReadAll(file)
fmt.Print(b)
}
但是有时,如果文件很大,则仅读取块(缓冲区大小)可能会更节省内存:因此,您可以使用 io.Reader.Read
的实现 * os.File
But sometimes, if the file size is big, it might be more memory-efficient to just read in chunks: buffer-size, hence you could use the implementation of io.Reader.Read
from *os.File
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
buf := make([]byte, 32*1024) // define your buffer size here.
for {
n, err := file.Read(buf)
if n > 0 {
fmt.Print(buf[:n]) // your read buffer.
}
if err == io.EOF {
break
}
if err != nil {
log.Printf("read %d bytes: %v", n, err)
break
}
}
}
否则,您也可以使用标准的util软件包: bufio
,尝试使用 Scanner
. Scanner
使用令牌(分隔符)读取文件.
Otherwise, you could also use the standard util package: bufio
, try Scanner
. A Scanner
reads your file in tokens: separator.
默认情况下,扫描程序将令牌按换行符前进(当然,您可以自定义扫描程序应如何对文件进行令牌化,请从此处了解 bufio测试).
By default, scanner advances the token by newline (of course you can customise how scanner should tokenise your file, learn from here the bufio test).
package main
import (
"fmt"
"os"
"log"
"bufio"
)
func main() {
file, err := os.Open("file.txt")
if err != nil {
log.Fatal(err)
}
defer func() {
if err = file.Close(); err != nil {
log.Fatal(err)
}
}()
scanner := bufio.NewScanner(file)
for scanner.Scan() { // internally, it advances token based on sperator
fmt.Println(scanner.Text()) // token in unicode-char
fmt.Println(scanner.Bytes()) // token in bytes
}
}
最后,我也想向您推荐这个很棒的网站: go-lang文件备忘单.它包含了与在go-lang中处理文件有关的几乎所有内容,希望您会发现它有用.
Lastly, I would also like to reference you to this awesome site: go-lang file cheatsheet. It encompassed pretty much everything related to working with files in go-lang, hope you'll find it useful.
这篇关于如何阅读文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!