donglu9134
2016-12-28 20:16
浏览 1.1k
已采纳

用Golang替换文件中的一行

I'm new to Golang, starting out with some examples. Currently, what I'm trying to do is reading a file line by line and replace it with another string in case it meets a certain condition. The file is use for testing purposes contains four lines:

one
two
three
four

The code working on that file looks like this:

 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 ...
")

         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 + "
")
   }

    file.Close()
 }

As you can see in the code snippet, I want to replace the string "two" with "This is a test" as soon as this string is read from the file. In order to get the current position within the file I use Go's Seek method. However, what happens is that always the last line gets replaced by This is a test, making the file looking like this:

one
two
three
This is a test

Examining the output of the print statement which writes the current file position to the terminal, I get that kind of output after 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

So after the first read, the position cursor already points to the end of my file, which explains why the new string gets appended to the end. Does anyone understand what is happening here or rather what is causing that behavior?

图片转代码服务由CSDN问答提供 功能建议

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

 一个
two 
three 
four 
   
 
 

在该文件上运行的代码如下:

 <代码> func main(){
 
文件,错误:= os.OpenFile(“ test.txt”,os.O_RDWR,0666)
 
(如果错误)  != nil {
 panic(err)
} 
 
 reader:= bufio.NewReader(file)
 
 for {
 
 fmt.Print(“尝试读取... 
”  )
 
 pos,_:= file.Seek(0,1)
 log.Printf(“文件中的位置是:%d”,pos)
字节,_,_:= reader.ReadLine()  
 
 if(len(bytes)== 0){
 break 
} 
 
 lineString:=字符串(字节)
 
 if(lineString ==“ two”){
文件。 寻求(int64(-(len(lineString))),1)
 file.WriteString(“这是一个测试。”)
} 
 
 fmt.Pr  intf(lineString +“ 
”)
} 
 
文件。Close()
} 
   
 
 

如代码段所示, 从文件中读取字符串后,我想立即将字符串“ two”替换为“ This is a test”。 为了获取文件中的当前位置,我使用Go的 Seek 方法 。 但是,发生的情况是总是将最后一行替换为这是一个测试,使文件看起来像这样:

 一个
two  
three 
这是一个测试
   
 
 

检查将当前文件位置写入终端的print语句的输出,在已读取第一行

  2016/12/28 21:10:31尝试读取... 
2016 / 12/28 21:  10:31文件中的位置是:19 
   
 
 

因此,在第一次读取后,位置光标已经指向我文件的末尾,这说明了为什么新字符串 被附加到末尾。 有人知道这里发生了什么,或者是什么导致了这种行为吗?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题