Featured image of post Go Mini Project: Reading and Filtering csv data

Go Mini Project: Reading and Filtering csv data

Learn how to read csv data and filter it using Go

Intro

This is a fun project to extract pokemon data from csv using Golang. This project was build by Ruby in this article

Steps

Open File

In the main file, firstly, we open up the file and put some necessery code to handle error and to close the file after complete.

1
2
3
4
5
	f, err := os.Open("pokemon.csv")
	if err != nil {
		log.Fatal("error open file", err)
	}
	defer f.Close()

Read File

Then we read the file using package bufio, buffered i/o, and stored in variable r.

1
r := bufio.NewReader(f)

Looping through lines

We then read all lines in the code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
	for {
		s, err := r.ReadString('\n')
		if err != nil && err.Error() != "EOF" {
			log.Println("error: ", err)
			break
		} else if err != nil && err.Error() == "EOF" {
			break
		}
		if strings.Contains(s, "Grass") {
			fmt.Print(s)
		}
	}

Improve the Code

Adding flag option

We add feature for adding costumization for path of the file and type of the Pokemon. By adding

1
2
3
4
	path := flag.String("path", "pokemon.csv", "path to the file that you want to load")
	pokemonType := flag.String("type", "Grass", "select your pokemon type")

	flag.Parse()

Then don’t forget to change hard code typing “Grass” with *pokemonType and “pokemon.csv” with *path

Incase Sensitive Input

Currently, You cannot search “Grass” by typing “grass”. By converting all data to lower case as well as input format, the search will be incase-sensitive.

1
2
3
4
5
...
		if strings.Contains(strings.ToLower(s),strings.ToLower(*pokemonType)) {
			fmt.Print(s)
		}
...

Final Code

Put all together in main.go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
...

func main() {

	path := flag.String("path", "pokemon.csv", "path to the file that you want to load")
	pokemonType := flag.String("type", "Grass", "select your pokemon type")

	flag.Parse()

	f, err := os.Open(*path)
	if err != nil {
		log.Fatal("error open file", err)
	}
	defer f.Close()

	r := bufio.NewReader(f)
	for {
		s, err := r.ReadString('\n')
		if err != nil && err.Error() != "EOF" {
			log.Println("error: ", err)
			break
		} else if err != nil && err.Error() == "EOF" {
			break
		}
		if strings.Contains(strings.ToLower(s), strings.ToLower(*pokemonType)) {
			fmt.Print(s)
		}
	}
}

I move the file location of “pokemon.csv” to another. Then test it by running go run . -path $HOME/Sandbox/file_source/pokemon.csv -type fire

comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy