Reading from csv file only prints last line

Hi there

I’m brand new to go so here goes…

I’m trying to read contents from a csv file. I have the following but when I run the code it only prints the last line of the csv file.

package main

import (

func main() {
	f, err := os.Open("data.csv")

	if err != nil {

	defer f.Close()

	r := csv.NewReader(f)

	for {
		record, err := r.Read()

		if err == io.EOF {

		if err != nil {


What am I doing wrong?

Maybe something with your csv?

I ran your code with data.csv:


And got for output:

[first_name last_name username]
[Rob Pike rob]
[Ken Thompson ken]
[Robert Griesemer gri]

Changing my data.csv to yours and then running the code I get

Robert Griesemer gri] username

I can’t work this out!

My csv file was created with an old version of Excel for Mac which apparently has issues with creating proper line endings.

On a Mac, Excel produces csv files with the wrong line endings, which causes problems for git (amongst other things).This issue plagues at least Excel 2008 and 2011, and possibly other versions. Basically, saving a file as comma separated values (csv) uses a carriage return \r rather than a line feed \n as a newline. Way back before OS X, this was actually the correct Mac file ending, but after the move to be more unix-y, the correct line ending should be \n. Given that nothing has used this as the proper line endings for over a decade, this is a bug.

Creating a new file blank file and pasting in the contents fixed it.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.