ioutil.WriteFile()

但是该示例文章在WRITE调用之后判断错误.

判断测试范围之外的错误:

    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
    }
ioutil.ReadFile

您需要在写入调用之后立即判断错误

            err = ioutil.WriteFile(fi.Name(), []byte(Value), 0644)
            check(err)   <===== too late

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

r := string(read)
r = strings.Replace(r, sam, strings.ToUpper(sam), -1)
err := ioutil.WriteFile(fi.Name(), []byte(r), 0644)
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)
\bsamsam
re := regexp.MustCompile("(?i)"+sam)