使用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\r\n"
for i:=0;i<5;i++{
writer.WriteString(str)
}
// 將緩沖區中的內容寫入到文件里
writer.Flush()
}
結果:
- 覆寫前:
- 覆寫后: