如何在golang中写入文件

use*_*581 17 go

我正在尝试写入文件.我阅读了文件的全部内容,现在我想根据文件中的一些单词更改文件的内容.但是当我检查文件的内容时,它仍然是相同的,并且没有改变.这就是我用过的东西

if strings.Contains(string(read), sam) {
    fmt.Println("this file contain that word")
    temp := strings.ToUpper(sam)
    fmt.Println(temp)
    err := ioutil.WriteFile(fi.Name(), []byte(temp), 0644)
} else {
    fmt.Println(" the word is not in the file")
}
Run Code Online (Sandbox Code Playgroud)

Von*_*onC 18

考虑到您的调用ioutil.WriteFile()与" 通过示例:编写文件 "中使用的内容一致,这应该可行.

但是,Go by example文章在写入调用之后检查错误.

您检查测试范围之外的错误:

    if matched {
        read, err := ioutil.ReadFile(path)
        //fmt.Println(string(read))
        fmt.Println(" This is the name of the file", fi.Name())
        if strings.Contains(string(read), sam) {
            fmt.Println("this file contain that word")
            Value := strings.ToUpper(sam)
            fmt.Println(Value)
            err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644)
        } else {
            fmt.Println(" the word is not in the file")
        }
        check(err)   <===== too late
    }
Run Code Online (Sandbox Code Playgroud)

您正在测试的错误是您在读取文件(ioutil.ReadFile)时获得的错误,因为块和范围.

您需要在写入呼叫后立即检查错误

            err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644)
            check(err)   <===== too late
Run Code Online (Sandbox Code Playgroud)

由于WriteFile会覆盖所有文件,因此可以使用strings.Replace()来替换大小写等效的单词:

r := string(read)
r = strings.Replace(r, sam, strings.ToUpper(sam), -1)
err := ioutil.WriteFile(fi.Name(), []byte(r), 0644)
Run Code Online (Sandbox Code Playgroud)

对于不区分大小写替换,请使用" 如何在Go中执行不区分大小写的正则表达式? "中的正则表达式.
使用func (*Regexp) ReplaceAllString:

re := regexp.MustCompile("(?i)\\b"+sam+"\\b")
r = re.ReplaceAllString(r, strings.ToUpper(sam))
err := ioutil.WriteFile(fi.Name(), []byte(r), 0644)
Run Code Online (Sandbox Code Playgroud)

请注意\b:单词边界以查找以内容开头和结尾的任何单词sam(而不是查找包含 sam内容的子字符串).
如果要替换子字符串,只需删除\b:

re := regexp.MustCompile("(?i)"+sam)
Run Code Online (Sandbox Code Playgroud)