How to write content to a file in Go? Use os.OpenFile() to open or create a file and return an *os.File object for writing. Use the io.WriteString() function to write a string directly to the io.Writer interface. Use bufio.Writer to provide buffered write operations and improve performance.
How to write content to a file in Go
The Go language provides a variety of methods to write content to a file. This article will introduce several of the most common methods and demonstrate them with practical examples.
Using os.OpenFile()
The os.OpenFile()
function allows you to open or create a file in a specified file mode. It returns an *os.File
object that can be used to write to a file.
package main import ( "fmt" "os" ) func main() { // 以可写模式打开或创建文件 f, err := os.OpenFile("test.txt", os.O_WRONLY|os.O_CREATE, 0644) if err != nil { fmt.Println(err) return } // 将内容写入文件 _, err = f.WriteString("Hello, world!") if err != nil { fmt.Println(err) return } // 关闭文件 if err := f.Close(); err != nil { fmt.Println(err) } }
Use io.WriteString()
io.WriteString()
function is a simpler way to write to a file. It writes strings directly to the io.Writer
interface.
package main import ( "fmt" "io" "os" ) func main() { // 以可写模式打开文件 f, err := os.OpenFile("test.txt", os.O_WRONLY|os.O_CREATE, 0644) if err != nil { fmt.Println(err) return } // 将内容写入文件 if _, err = io.WriteString(f, "Hello, world!\n"); err != nil { fmt.Println(err) return } // 关闭文件 if err := f.Close(); err != nil { fmt.Println(err) } }
Use bufio.Writer
##bufio.Writer provides buffered write operations, which can improve performance.
package main import ( "fmt" "io" "os" "bufio" ) func main() { // 以可写模式打开文件 f, err := os.OpenFile("test.txt", os.O_WRONLY|os.O_CREATE, 0644) if err != nil { fmt.Println(err) return } // 使用 bufio.Writer 进行缓冲写入 w := bufio.NewWriter(f) if _, err = w.WriteString("Hello, world!\n"); err != nil { fmt.Println(err) return } // 务必刷新缓冲区以将数据写入文件 if err := w.Flush(); err != nil { fmt.Println(err) return } // 关闭文件 if err := f.Close(); err != nil { fmt.Println(err) } }
The above is the detailed content of How to write content to file using Golang?. For more information, please follow other related articles on the PHP Chinese website!