golang can open a file for reading and writing (r+) or writing (w+). This is for files on the hard disk, not on the cloud.
In this article we will cover how to write files in golang. If you are interested in reading files, see tthe read-file article instead.
Write files in golang
Write file
The golang program below writes a file from the disk. If the file exists, it will be overwritten (w+). If you want to add to end of the file instead, use (a+).
// Write file in go. You don't need to set any flags.
// This will overwrite the file if it already exists
package main
import "os"
func main() {
file, err := os.Create("file.txt")
if err != nil {
return
}
defer file.Close()
file.WriteString("write file in golang")
}
This writes the golang string into the newly created file. If you get an error, it means you don’t have the right user permissions to write a file (no write access) or that the disk is full.
Otherwise the new file has been created (file.txt). This file contains the string contents which you can see with any text editor.
Flags
If you use the w+ flag the file will be created if it doesn’t exist. The w+ flag makes golang overwrite the file if it already exists.
The r+ does the same, but golang then allows you to read files. Reading files is not allowed with the w+ flag.
If you want to append to a file (add) you can use the a+ flag. This will not overwrite the file, only append the end of the file.
Exercises
- Write a list of cities to a new file.