


The Writer will send data when the buffer is either full or when explicitly flushed. The shortest way of writing data to a file is to use the os.WriteFile() function. This tutorial has the following sections. Write the entire content to a file at once. Moreover, this function is defined under the io package. And if w is implemented by StringWriter then its WriteString method is called immediately. We will also learn how to write to a file concurrently. The WriteString () function in Go language is used to write the contents of the stated string s to the writer w, which takes a slice of bytes. You’ll note the use of bufio NewWriter and method Writer.Flush. In this tutorial, we will learn how to write data to files using Go. 23 minutes ago by Oleksiy Kondratiev 9 min read Dive into the mesmerizing world of Golang as we uncover various methods to write files. Overwrite file if it exists: file, err := os.OpenFile("/path/to/file", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)Ĭreate file if it doesn’t exist, else append to it: file, err := os.OpenFile("/path/to/file", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) Write a text file line-by-line full exampleīelow is a common example writing a text file line by line in Golang. One of the first three flags below must be provided in the OpenFile function. The Golang OS package OpenFile function opens files using flags and permissions. We will be heavily leveraging standard library packages like os, bufio, bytes and fmt. A buffered writer queues up bytes until a threshold is reach then completes the write operation to minimize resources. We will be performing write operations like appending, deleting, and replacing a file using golang. The bufio package provides an efficient buffered writer.
