I'm unable to find file.ReadLine
function in Go. I can figure out how to quickly write one, but just wondering if I'm overlooking something here. How does one read a file line by line?
相关问题
- Correctly parse PDF paragraphs with Python
- how to split a list into a given number of sub-lis
- What is the best way to do a search in a large fil
- Generate string from integer with arbitrary base i
- R: eval(parse()) error message: cannot ope
相关文章
- Can I run a single test in a suite?
- JSP String formatting Truncate
- Selecting only the first few characters in a strin
- How do I get from a type to the TryParse method?
- How to check if a request was cancelled
- What is the correct way to declare and use a FILE
- Is it possible to implement an interface with unex
- Python: print in two columns
EDIT: As of go1.1, the idiomatic solution is to use bufio.Scanner
I wrote up a way to easily read each line from a file. The Readln(*bufio.Reader) function returns a line (sans \n) from the underlying bufio.Reader struct.
You can use Readln to read every line from a file. The following code reads every line in a file and outputs each line to stdout.
Cheers!
There two common way to read file line by line.
In my testcase, ~250MB, ~2,500,000 lines, bufio.Scanner(time used: 0.395491384s) is faster than bufio.Reader.ReadString(time_used: 0.446867622s).
Source code: https://github.com/xpzouying/go-practice/tree/master/read_file_line_by_line
Read file use bufio.Scanner,
Read file use bufio.Reader,
You can also use ReadString with \n as a separator:
Example from this gist
but this gives an error when there is a line that larger than Scanner's buffer.
When that happened, what I do is use
reader := bufio.NewReader(inFile)
create and concat my own buffer either usingch, err := reader.ReadByte()
orlen, err := reader.Read(myBuffer)
In Go 1.1 and newer the most simple way to do this is with a
bufio.Scanner
. Here is a simple example that reads lines from a file:This is the cleanest way to read from a
Reader
line by line.There is one caveat: Scanner does not deal well with lines longer than 65536 characters. If that is an issue for you then then you should probably roll your own on top of
Reader.Read()
.