Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - WRITE TO FILE


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'.


In a huge pond,
there lived many fish.
They were arrogant and
never listened to anyone.

Example :



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()
    
}


Output :



 File created

Now, if you open the File, 'myfirstfile.txt', you can find the below contents,


java_Collections
  1. So, what we have done in the above example is, created a new file with name 'myfirstfile.txt', using the 'os.Create()' passing the file name 'myfirstfile.txt' to it.

    myfile, error := os.Create("myfirstfile.txt")


    Now, if you see on the Right Hand Side, there are two variables 'myfile' and 'error'.'myfile' is the variable we will be using to write to a file. And 'error' is the variable that comes into effect only if there is an error.
  2. In the next line we check, if an error has occurred or not.

    if error != nil { 
        fmt.Println("Couldn't create file") 
    }	
           
  3. Then we have initialised the paragraph in a variable, 'para' using "``".

    para = `In a huge pond,
    there lived many fish.
    They were arrogant and
    never listened to anyone.`
  4. After that we have used the 'WriteString()' Function to write the paragraph to the file.

    myfile.WriteString(para)
  5. Finally, we close the file using the 'defer' and 'Close()' Function.

    defer myfile.Close()

Now, let us say, we want to add three more lines to the above file.


In this pond,
there also lived
a kind-hearted crocodile.

The 'os.O_APPEND' ca be used with 'OpenFile()' function to append values to the existing file.


Example :



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 ") 
    
}


Output :



 File updated

Now, if you open the File, 'myfirstfile.txt', you can find the below contents,


java_Collections