我想做这个:
我的第一个想法是用 将整个文件读入内存ioutil.Readfile(),
但我不确定如何在处理完该行后更新文本文件,
以及如果在文本文件被读入后将额外的行添加到文本文件中会发生什么记忆?
我通常编写 shell 脚本,并会做这样的事情:
while read -r line; do
echo "${line}"
sed -i 1d "${myList}"
done < "${myList}"
Run Code Online (Sandbox Code Playgroud)
在 Golang 中执行此操作的最佳方法是什么?
使用bufio包。
这是打开文本文件并遍历每个line.
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)
}
}
Run Code Online (Sandbox Code Playgroud)