在 Go 中逐行读取文件 [英] Reading a file line by line in Go

查看:39
本文介绍了在 Go 中逐行读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Go 中找不到 file.ReadLine 函数.我可以弄清楚如何快速写一个,但我只是想知道我是否在这里忽略了一些东西.如何逐行读取文件?

I'm unable to find file.ReadLine function in Go. I can figure out how to quickly write one, but I am just wondering if I'm overlooking something here. How does one read a file line by line?

推荐答案

注意: 接受的答案在 Go 的早期版本中是正确的.查看投票最高的答案包含实现此目标的最新惯用方法.

NOTE: The accepted answer was correct in early versions of Go. See the highest voted answer contains the more recent idiomatic way to achieve this.

bufio 包中有ReadLine 函数.

请注意,如果该行不适合读取缓冲区,该函数将返回一个不完整的行.如果您想始终通过一次调用函数来读取程序中的整行,则需要将 ReadLine 函数封装到您自己的函数中,该函数调用 ReadLine一个 for 循环.

Please note that if the line does not fit into the read buffer, the function will return an incomplete line. If you want to always read a whole line in your program by a single call to a function, you will need to encapsulate the ReadLine function into your own function which calls ReadLine in a for-loop.

bufio.ReadString(' ') 并不完全等同于 ReadLine,因为 ReadString 无法处理当文件的最后一行不以换行符结尾.

bufio.ReadString(' ') isn't fully equivalent to ReadLine because ReadString is unable to handle the case when the last line of a file does not end with the newline character.

这篇关于在 Go 中逐行读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆