dsg56465 2017-05-11 08:36
浏览 551

在Go中从CSV文件读取仅打印最后一行

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.

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

    if err != nil {
        log.Fatal(err)
    }

    defer f.Close()

    r := csv.NewReader(f)

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

        if err == io.EOF {
            break
        }

        if err != nil {
            log.Fatal(err)
        }

        fmt.Println(record)
    }
}

// Returns
10 3311 74209 OM209] site

What am I doing wrong?

data.csv

Item,clientid,ident,site
1,2493,83982,OM221
2,2509,85764,OM201
3,2535,70264,OM205
4,2608,70648,OM205
5,2766,83647,OM304
6,2871,69400,OM201
7,2933,80024,OM201
8,2994,77827,OM301
9,3206,73315,OM201
10,3311,74209,OM209
  • 写回答

1条回答 默认 最新

  • duanlun4411 2017-05-11 10:11
    关注

    Thanks to @Volker for the mention about proper line endings.

    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 rather than a line feed 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 . Given that nothing has used this as the proper line endings for over a decade, this is a bug.

    https://nicercode.github.io/blog/2013-04-30-excel-and-line-endings/

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

    评论

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败