我正在尝试写入文件。我阅读了文件的全部内容,现在我想根据我从文件中获得的一些单词更改文件的内容。但是当我检查文件的内容时,它仍然是相同的,并且没有改变。这是我用过的
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")
}
答案 0 :(得分:16)
考虑到您对ioutil.WriteFile()
的调用与“Go by Example: Writing Files”中使用的内容一致,这应该有效。
但是,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
}
您正在测试的错误是您在阅读文件(ioutil.ReadFile
)时得到的错误,因为blocks and scope。
您需要在写入呼叫后立即检查错误
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)
对于不区分大小写的,请使用“How do I do a case insensitive regular expression in 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)
请注意\b
: word boundary ,以查找以sam
内容开头和结尾的任何字(而不是查找子字符串包含 sam
内容)。
如果要替换子字符串,只需删除\b
:
re := regexp.MustCompile("(?i)"+sam)
答案 1 :(得分:2)
目前尚不清楚自己想做什么。我最好的猜测是这样的:
package main
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
)
func UpdateWord(filename string, data, word []byte) (int, error) {
n := 0
f, err := os.OpenFile(filename, os.O_WRONLY, 0644)
if err != nil {
return n, err
}
uWord := bytes.ToUpper(word)
if len(word) < len(uWord) {
err := errors.New("Upper case longer than lower case:" + string(word))
return n, err
}
if len(word) > len(uWord) {
uWord = append(uWord, bytes.Repeat([]byte{' '}, len(word))...)[:len(word)]
}
off := int64(0)
for {
i := bytes.Index(data[off:], word)
if i < 0 {
break
}
off += int64(i)
_, err = f.WriteAt(uWord, off)
if err != nil {
return n, err
}
n++
off += int64(len(word))
}
f.Close()
if err != nil {
return n, err
}
return n, nil
}
func main() {
// Test file
filename := `ltoucase.txt`
// Create test file
lcase := []byte(`update a bc def ghij update klmno pqrstu update vwxyz update`)
perm := os.FileMode(0644)
err := ioutil.WriteFile(filename, lcase, perm)
if err != nil {
fmt.Println(err)
return
}
// Read test file
data, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(data))
// Update word in test file
word := []byte("update")
n, err := UpdateWord(filename, data, word)
if err != nil {
fmt.Println(n, err)
return
}
fmt.Println(filename, string(word), n)
data, err = ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(data))
}
输出:
update a bc def ghij update klmno pqrstu update vwxyz update
ltoucase.txt update 4
UPDATE a bc def ghij UPDATE klmno pqrstu UPDATE vwxyz UPDATE