How to append to a file in Golang
Golang allows us to append or add data to an already existing file. We will use its built-in package called os with a method OpenFile() to append text to a file.
The os.OpenFile() function
To use the os.OpenFile() function, we first need to import the os package in our Go file as follows:
import "os"
Syntax
The prototype of the os.OpenFile() function is shown below:
os.OpenFile(name/path string, flag int, perm FileMode)
Parameters
The os.OpenFile() function takes the following parameters:
name/path: The name of the file, e.g., “example.txt,” if the file is in the current directory or the complete path of the file if it is present in another directory. The data type of this parameter isstring.flag: Aninttype instruction given to the method to open the file, e.g., read-only, write-only, or read-write. Commonly used flags are as follows:O_RDONLY: It opens the file read-only.O_WRONLY: It opens the file write-only.O_RDWR: It opens the file read-write.O_APPEND: It appends data to the file when writing.O_CREATE: It creates a new file if none exists.
perm: A numeric value of the mode that we wantos.OpenFile()to execute in, e.g., read-only has a value of 4 and write-only has a value of 2.
Return values
The os.OpenFile() method returns two values:
File: AFileon which different operations such as write or append can be performed based on the file mode passed to the function*PathError: An error while opening or creating the file.
Code
The code below shows the use of the os.OpenFile() to append data to a file:
This is old text. New text =>
Note: After the message '
Operation successful! Text has been appended to example.txt' is displayed on the terminal, please type 'cat example.txt' in the terminal to verify the updates in the file. You will find that new text is appended after the 'New text =>' text.
Explanation
First, we import the required Go packages. The fmt package allows us to print something on the console. In this case, errors related to file reading or writing are printed. The os package is imported to use the os.OpenFile() method.
-
Line 10: We open
example.textusingos.OpenFile()with theos.O_Appendflag because we want to append data to the file.os.OpenFile()allows us to provide multiple flags for efficiency by using theOR(|)operator. Here, we provide theos.O_CREATEflag ifexample.txtdoes not exist. Since we write to the file, theos.O_WRONLYflag specifies write-only mode.0644is the numerical representation of all these flags. -
Line 12: We check any error in opening the file. If an error exists, the program ends.
-
Line 17: We delay the closing of the file until the end of the program using the built-in keyword
defer. -
Line 19: We use the built-in
writeString()function to the file opened byos.OpenFile(). -
Line 21: The error in writing to the file is checked.