So, let us see, how can we write something to the file.
So, the first thing we need to do is, create the file, 'myfirstfile.txt'.
Then write the below contents to the file, 'myfirstfile.txt'.
package main import "fmt" import "os" func main() { myfile, error := os.Create("myfirstfile.txt") if error != nil { fmt.Println("Couldn't create file") } para := `In a huge pond, there lived many fish. They were arrogant and never listened to anyone.` myfile.WriteString(para) fmt.Println("File created ") defer myfile.Close() }
Now, if you open the File, 'myfirstfile.txt', you can find the below contents,
if error != nil { fmt.Println("Couldn't create file") }
Now, let us say, we want to add three more lines to the above file.
The 'os.O_APPEND' ca be used with 'OpenFile()' function to append values to the existing file.
package main import "fmt" import "os" func main() { myfile, error := os.OpenFile("myfirstfilego.txt", os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) if error != nil { fmt.Println("Couldn't create file") } para := `In this pond, there also lived a kind-hearted crocodile.` defer myfile.Close() myfile.WriteString(para) fmt.Println("File updated ") }
Now, if you open the File, 'myfirstfile.txt', you can find the below contents,