Golangでcsvファイルから、特定の行の数値を読み出す

「Golangでcsvファイルを読み出す」の記事は多いのですが、特定の行まで引っ張り出す情報があまりないので、メモを残しておきます。

/*
以下のcsvファイル(kai_20220522holyday18.csv)の中身を取り出す
id,age,type,departure_name,departure_number,departure_lat,departure_lng,arrival_name,arrival_number,arrival_lat,arrival_lng
0,43,resident,,,34.173408,131.470684,,,34.155862,131.501246
1,24,resident,,,34.179449,131.482543,,,34.164116,131.471791
2,42,resident,,,34.168739,131.470768,,,34.160989,131.491124
3,21,resident,,,34.169494,131.469934,,,34.173498,131.471351
4,58,resident,,,34.185295,131.47414,,,34.191481,131.49456
5,48,resident,,,34.150778,131.480747,,,34.16536,131.471872
6,56,resident,,,34.16536,131.471872,,,34.174066,131.479312
7,73,resident,,,34.155731,131.500845,,,34.16776,131.472831
8,47,resident,,,34.167237,131.471785,,,34.155775,131.476531
9,21,resident,,,34.154931,131.50468,,,34.156678,131.49581
10,37,resident,,,34.16727,131.472899,,,34.171253,131.471177
11,40,resident,,,34.147241,131.474921,,,34.150675,131.486268
12,67,resident,,,34.173683,131.476347,,,34.173643,131.471027
13,28,resident,,,34.183079,131.484303,,,34.174245,131.474592
14,46,resident,,,34.146154,131.472711,,,34.159611,131.491548
15,25,resident,,,34.162497,131.489283,,,34.147212,131.475984
*/

package main

import (
	"encoding/csv"
	"fmt"
	"log"
	"os"
	"strconv"
)

func main() {
	file, err := os.Open("kai_20220522holyday18.csv") // 先ほど入手した郵便番号データをos.Openで開く
	if err != nil {
		log.Fatal(err)
	}
	defer file.Close()

	r := csv.NewReader(file)
	rows, err := r.ReadAll() // csvを一度に全て読み込む
	if err != nil {
		log.Fatal(err)
	}

	// 行ごとに
	for i, row := range rows {
		if i == 0 {
			continue // CSVのヘッダー行を無視
		}

		age := row[1]

		departure_lat, err := strconv.ParseFloat(row[5], 64)
		if err != nil {
			log.Fatal(err)
		}
		departure_lng, err := strconv.ParseFloat(row[6], 64)
		if err != nil {
			log.Fatal(err)
		}

		arrival_lat, err := strconv.ParseFloat(row[9], 64)
		if err != nil {
			log.Fatal(err)
		}

		arrival_lng, err := strconv.ParseFloat(row[10], 64)
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(age, departure_lat, departure_lng, arrival_lat, arrival_lng)

	}
}

 

出力結果

C:\Users\ebata\yamaguchi\src_try1\others> go run main5.go
43 34.173408 131.470684 34.155862 131.501246
24 34.179449 131.482543 34.164116 131.471791
42 34.168739 131.470768 34.160989 131.491124
21 34.169494 131.469934 34.173498 131.471351
58 34.185295 131.47414 34.191481 131.49456
56 34.16536 131.471872 34.174066 131.479312
73 34.155731 131.500845 34.16776 131.472831
47 34.167237 131.471785 34.155775 131.476531
21 34.154931 131.50468 34.156678 131.49581
37 34.16727 131.472899 34.171253 131.471177
40 34.147241 131.474921 34.150675 131.486268
67 34.173683 131.476347 34.173643 131.471027
28 34.183079 131.484303 34.174245 131.474592
46 34.146154 131.472711 34.159611 131.491548
25 34.162497 131.489283 34.147212 131.475984

 

2023,江端さんの技術メモ

Posted by ebata