首頁  >  文章  >  後端開發  >  如何在go中的特定字串之前附加到檔案?

如何在go中的特定字串之前附加到檔案?

王林
王林轉載
2024-02-05 21:15:08403瀏覽

如何在go中的特定字串之前附加到檔案?

問題內容

我有一個以此結構開頭的檔案:

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”,您可以執行以下操作。

  1. 以讀取/寫入模式開啟檔案。
  2. 根據檔案建立掃描器,並將每一行掃描到記憶體中。
  3. 掃描時檢查每一行,看看是否遇到包含「//」的行。
  4. 將每一行保存在陣列中,以便稍後將其寫回檔案。
  5. 如果找到該行,請附加新行“e”,並更新上一行。
  6. 將這些行寫回檔案。
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中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除