gpt4 book ai didi

csv - 从 Go 中的 csv 文件读取只打印最后一行

转载 作者:IT王子 更新时间:2023-10-29 02:22:00 27 4
gpt4 key购买 nike

我正在尝试从 csv 文件中读取内容。我有以下内容,但是当我运行代码时,它只打印 csv 文件的最后一行。

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

我做错了什么?

数据.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

最佳答案

感谢@Volker 提到正确的行结尾。

我的 csv 文件是使用旧版本的 Excel for Mac 创建的,显然在创建正确的行尾时存在问题。

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.

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

创建一个新文件空白文件并粘贴内容修复它。

关于csv - 从 Go 中的 csv 文件读取只打印最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43910451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com