
我有一个以此结构开头的文件:
locals {
my_list = [
"a",
"b",
"c",
"d"
//add more text before this
]
}我想在“//在此之前添加更多文本”之前添加文本“e”,在“d”之后添加“,”,所以它会像这样:
locals {
MY_LIST = [
"a",
"b",
"c",
"d",
"e"
//add more text before this
]
}如何动态实现此功能,以便将来可以向文件添加更多字符串?
谢谢
要在以“//”开头的行之前添加文本“e”,您可以执行以下操作。
func main() {
f, err := os.OpenFile("locals.txt", os.O_RDWR, 0644)
if err != nil {
log.Fatal(err)
}
scanner := bufio.NewScanner(f)
lines := []string{}
for scanner.Scan() {
ln := scanner.Text()
if strings.Contains(ln, "//") {
index := len(lines) - 1
updated := fmt.Sprintf("%s,", lines[index])
lines[index] = updated
lines = append(lines, " \"e\"", ln)
continue
}
lines = append(lines, ln)
}
content := strings.Join(lines, "\n")
_, err = f.WriteAt([]byte(content), 0)
if err != nil {
log.Fatal(err)
}
}
以上就是如何在go中的特定字符串之前附加到文件?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号