1. How to create empty file in Go
package main
import "os"
func main() {
file, _ := os.Create("/tmp/go.txt")
defer file.Close()
}
- /tmp/go.txt - path to file to create
2. How to create new or overwrite existing file with new content in Go
package main
import "os"
func main() {
f, _ := os.OpenFile("/tmp/go.txt", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
defer f.Close()
f.WriteString("new content\n")
}
- /tmp/go.txt path to file to create/overwrite
- os.O_RDWR|os.O_CREATE|os.O_TRUNC means we will either create new or truncate existing file before writing content
- new content\n new content to write to file
3. How to append line to existing file in Go
package main
import "os"
func main() {
f, _ := os.OpenFile("/tmp/go.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
defer f.Close()
f.WriteString("new line\n")
}
Here, we're appending "new line\n" text (with new line symbol at the end) to /tmp/go.txt file. In order to make that right, we need to set os.O_APPEND|os.O_CREATE|os.O_WRONLY permissions.
4. How to read file contents to a string variable:
package main
import "os"
func main() {
t, _ := os.ReadFile("/tmp/go.txt")
str := string(t)
}
Here we read everything from /tmp/go.txt file to str
variable. Note we're converting read bytes to string using string()
function.
Top comments (0)