douhe4608 2014-10-02 00:48
浏览 340
已采纳

替换文本文件Golang中的一行

How do I replace a line in a text file with a new line?

Assume I've opened the file and have every line in an array of string objects i'm now looping through

//find line with ']'
    for i, line := range lines {

        if strings.Contains(line, ']') {


            //replace line with "LOL"
            ?
        }
    }
  • 写回答

1条回答 默认 最新

  • dtvpe4837413 2014-10-02 01:18
    关注

    What matters here is not so much what you do in that loop. It's not like you're gonna be directly editing the file on the fly.

    The most simple solution for you is to just replace the string in the array and then write the contents of the array back to your file when you're finished.

    Here's some code I put together in a minute or two. It properly compiles and runs on my machine.

    package main
    
    import (
            "io/ioutil"
            "log"
            "strings"
    )
    
    func main() {
            input, err := ioutil.ReadFile("myfile")
            if err != nil {
                    log.Fatalln(err)
            }
    
            lines := strings.Split(string(input), "
    ")
    
            for i, line := range lines {
                    if strings.Contains(line, "]") {
                            lines[i] = "LOL"
                    }
            }
            output := strings.Join(lines, "
    ")
            err = ioutil.WriteFile("myfile", []byte(output), 0644)
            if err != nil {
                    log.Fatalln(err)
            }
    }
    

    There's a gist too (with the same code) https://gist.github.com/dallarosa/b58b0e3425761e0a7cf6

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝