我想这样做:
- 从文本文件中读取一行。
- 处理行。
- 删除该行。
我的第一个想法是使用 ioutil.Readfile()
将整个文件读入内存,
但我不确定如何在处理完该行后更新文本文件,
如果在将文本文件读入内存后将额外的行添加到文本文件中会发生什么情况?
我通常会编写 shell 脚本,并且会做这样的事情:
while read -r line; do
echo "${line}"
sed -i 1d "${myList}"
done < "${myList}"
在 Golang 中执行此操作的最佳方法是什么?
最佳答案
使用 bufio
包。
下面是打开文本文件并遍历每一行 的基本语法。
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
// Open the file.
f, _ := os.Open("C:\\programs\\file.txt")
// Create a new Scanner for the file.
scanner := bufio.NewScanner(f)
// Loop over all lines in the file and print them.
for scanner.Scan() {
line := scanner.Text()
fmt.Println(line)
}
}
关于go - 从 Golang 中的文本文件中读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38684841/