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

查看:98
本文介绍了在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函数封装到自己的函数中,该函数在for循环中调用ReadLine.

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('\n')并不完全等同于ReadLine,因为ReadString无法处理文件的最后一行不以换行符结尾的情况.

bufio.ReadString('\n') 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天全站免登陆