Read a tab-separated file into a map

This example Go program illustrates reading a tab-separated file into a map.

package main

import (

func readLines(path string) (map[string] string, error) {
        file, err := os.Open(path)
        if err != nil {
                return nil, err
        defer file.Close()

        lines := make(map[string]string)
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
                pair := strings.SplitN(scanner.Text(), "\t", 2)
                lines[pair[0]] = pair[1]
        return lines, scanner.Err()

func main() {
        lines, err := readLines("fruit.txt")
        if err != nil {
                log.Fatalf("readLines: %s", err)
        for i := range lines {
                fmt.Printf ("%s is a %s fruit\n", lines[i], i)


The input file looks like this

orange	orange
yellow	lemon
green	lime

The output looks like this

orange is a orange fruit
lemon is a yellow fruit
lime is a green fruit

Copyright © Ben Bullock 2009-2021. All rights reserved. For comments, questions, and corrections, please email Ben Bullock ( or use the discussion group at Google Groups. News about the site. / Privacy / Disclaimer