14

I am new to go lang. I am able to create a new file from the terminal using go script. like this

go run ../myscript.go > ../filename.txt

but I want to create the file from the script.

package main

import "fmt"

func main() {
    fmt.Println("Hello") > filename.txt
}

3 Answers 3

23

If you are trying to print some text to a file one way to do it is like below, however if the file already exists its contents will be lost:

package main

import (
    "fmt"
    "os"
)

func main() {
    err := os.WriteFile("filename.txt", []byte("Hello"), 0755)
    if err != nil {
        fmt.Printf("Unable to write file: %v", err)
    }
}

The following way will allow you to append to an existing file if it already exists, or creates a new file if it doesn't exist:

package main

import (
    "os"
    "log"
)


func main() {
    // If the file doesn't exist, create it, or append to the file
    f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
    if err != nil {
        log.Fatal(err)
    }
   
    _, err = f.Write([]byte("Hello"))
    if err != nil {
        log.Fatal(err)
    }

    f.Close()
}
1

you just need to check the API documentation. This is one way to do it, there is others (with os or bufio)

package main

import (
    "io/ioutil"
)

func main() {
    // read the whole file at once
    b, err := ioutil.ReadFile("input.txt")
    if err != nil {
        panic(err)
    }

    // write the whole body at once
    err = ioutil.WriteFile("output.txt", b, 0644)
    if err != nil {
        panic(err)
    }
}
1

Fprintln is pretty close to what you were trying to do:

package main

import (
   "fmt"
   "os"
)

func main() {
   f, e := os.Create("filename.txt")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   fmt.Fprintln(f, "Hello")
}

https://golang.org/pkg/fmt#Fprintln

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.