首页 文章

用Golang替换文件中的一行

提问于
浏览
3

我是Golang的新手,从一些例子开始 . 目前,我要做的是逐行读取文件,并在满足特定条件时将其替换为另一个字符串 . 该文件用于测试目的包含四行:

one
two
three
four

处理该文件的代码如下所示:

func main() {

     file, err := os.OpenFile("test.txt", os.O_RDWR, 0666)

     if err != nil {
       panic(err)
     }

     reader := bufio.NewReader(file)

      for {

         fmt.Print("Try to read ...\n")

         pos,_ := file.Seek(0, 1)
         log.Printf("Position in file is: %d", pos)
         bytes, _, _ := reader.ReadLine()

         if (len(bytes) == 0) {
            break
         }

         lineString := string(bytes)

         if(lineString == "two") {
             file.Seek(int64(-(len(lineString))), 1)
             file.WriteString("This is a test.")
         }

         fmt.Printf(lineString + "\n")
   }

    file.Close()
 }

正如您在代码片段中看到的,我想在从文件中读取此字符串后立即将字符串"two"替换为"This is a test" . 为了获得文件中的当前位置,我使用Go的Seek方法 . 然而,发生的是总是最后一行被替换为这是一个测试,使文件看起来像这样:

one
two
three
This is a test

检查将当前文件位置写入终端的print语句的输出,我在 the first line has been read 之后得到那种输出:

2016/12/28 21:10:31 Try to read ...
2016/12/28 21:10:31 Position in file is: 19

所以在第一次读取之后,位置光标已经指向我文件的末尾,这解释了为什么新字符串被附加到结尾 . 有谁知道这里发生了什么,或者更确切地说是什么导致了这种行为?

1 回答

  • 3

    读者不是 file.Seek 的控制者 . 您已将阅读器声明为: reader := bufio.NewReader(file) 然后您一次读取一行 bytes, _, _ := reader.ReadLine() 但是 file.Seek 不会更改阅读器正在读取的位置 .

    建议你阅读文档中的ReadSeeker并切换到使用它 . 还有一个使用SectionReader的例子 .

相关问题