douhe4608 2014-10-01 16: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-01 17: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

    展开全部

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部