Golang打开已存在的文件并覆盖其内容

使用os.OpenFile()打开文件,flag选择 O_WRONLY|O_TRUNC 即可

具体代码

import (
	"fmt"
	"os"
	"bufio"
)


func main(){
	// 打开一个存在的文件,将原来的内容覆盖掉
	path := "./hello.txt"
	// O_WRONLY: 只写, O_TRUNC: 清空文件
	file, err := os.OpenFile(path, os.O_WRONLY | os.O_TRUNC, 0666)
	if err!=nil{
		fmt.Println("文件打开错误", err)
		return
	}

	defer file.Close()// 关闭文件
	// 带缓冲区的*Writer
	writer := bufio.NewWriter(file)
	str := "hello golang
"
	for i:=0;i<5;i++{
		writer.WriteString(str)
	}

	// 将缓冲区中的内容写入到文件里
	writer.Flush()
}

结果

  • 覆写前:
  • 覆写后:
原文地址:https://www.cnblogs.com/pangqianjin/p/14402087.html