Reading Files: .TXT .CSV
Reading Files: .TXT .CSV
format-agnostic. What this means is that you’ll be able to use the techniques
we’ll be covering in order to read and write, .txt, .csv, .xls and so on, the
only thing that differs for these files is the structure of the data that you write
to each of these file types.
Reading Files
In order to read from files on your local file system, you’ll have to use
the io/ioutil module. You’ll first have to pull of the contents of a file into
memory by calling ioutil.Read File("/path//my/file.ext") which will take
in the path to the file you wish to read in as it’s only parameter. This will return
either the data of the file, or an error which can be handled as you normally
handle errors in go.
package main
import (
"fmt"
"io/ioutil"
func main() {
if err != nil {
fmt.Println(err)
fmt.Print(string(data))
As you can see, we’ve successfully managed to read all of the data stored
within our proprietary localfile.data file type.
In order to write content to files using Go, we’ll again have to leverage
the io/ioutil module. We’ll first have to construct a byte array that represents
the content we wish to store within our files.
if err != nil {
// print it out
fmt.Println(err)
}
Let’s expand our original main.go file to not only read, but to write to a file as
well:
package main
import (
"fmt"
"io/ioutil"
func main() {
if err != nil {
// print it out
fmt.Println(err)
}
data, err := ioutil.ReadFile("myfile.data")
if err != nil {
fmt.Println(err)
fmt.Print(string(data))
If you attempt to run this now by calling go run main.go, you should see that
a new file is automatically created within your current directory
called myfile.data and our go program proceeds to read from this newly
created file and prints the contents in the console:
➜ go run main.go
import (
"fmt"
"io/ioutil"
"os"
func main() {
if err != nil {
// print it out
fmt.Println(err)
}
data, err := ioutil.ReadFile("myfile.data")
if err != nil {
fmt.Println(err)
fmt.Print(string(data))
if err != nil {
panic(err)
defer f.Close()
panic(err)
if err != nil {
fmt.Println(err)
}
fmt.Print(string(data))
Now that you have added the new code, we can test it out by running
our main.go file:
$ go run main.go
File Permissions
It’s incredibly important to understand the various different file permissions
available to you when you are writing to new files.