go如何更新文本文件中某一行的内容

kekemuyu · · 5408 次点击
这样是不是效率太低了
#5
更多评论
是不是reader := bufio.NewReader(fi)被创建后,如果改变fi文件的内容,reader也会改变
#1
我是这样写的,测试文件:1.txt this is the test file line 1 my name is hhh #name=my year's old 18 Name=wangyunan return restult 把第四行的 Name=wangyunan替换成Name=wang yu nan 代码: package main import ( "bufio" "fmt" "io" "os" "strings" ) func main() { oldFile := "./1.txt" f, err := os.Open(oldFile) if err != nil { fmt.Println("文件打开失败") return } defer f.Close() buf := bufio.NewReader(f) var rep = []string{"Name=wang yu nan"} var result = "" // 逐行读取 for { a, _, err := buf.ReadLine() if err == io.EOF { fmt.Println("文件读取完毕") break } if strings.Contains(string(a), "Name=wangyunan") { result += strings.Join(rep, "") + "\n" } else { result += string(a) + "\n" } } // 清空文件重新写入数据 fw, err := os.OpenFile(oldFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666) if err != nil { fmt.Println("文件打开失败,请检查") return } defer fw.Close() w := bufio.NewWriter(fw) w.WriteString(result) if err != nil { panic(err) } w.Flush() } 最后输出: this is the test file line 1 my name is hhh #name=my year's old 18 Name=wang yu nan return restult
#2