【2022-09-26】golang文件流八秃,逐行讀取

    file, err := os.Open("textName.csv")
    if err != nil {
        return nil, err
    }
    defer file.Close()

    buf := []byte{}
    scanner := bufio.NewScanner(file)
    scanner.Buffer(buf, 4096*1024)

    for scanner.Scan() {
        str := scanner.Text()
               // do something

    }

詳細(xì)講解:https://devmarkpro.com/working-big-files-golang


轉(zhuǎn)載:
Today, I am going to show you how to read files in golang line-by-line. Let's imagine that have a jsonl file. What's jsonl? it's json lines in a simple term, it's a file that each line of it represents a valid json object. So if we read the file line by line, we can Marshal/Unmarshal each line of it separately. Here's an example of a jsonl file.

Each line of this file represents the data of a world cup.

COPY

{"year":"2018","host":"Russia","winner":"France"}
{"year":"2014","host":"Brazil","winner":"Germany"}
{"year":"2010","host":"South Africa","winner":"Spain"}
{"year":"2006","host":"Germany","winner":"Italy"}

Working with bufio.Scanner

So let’s read this file line by line most easily and conveniently. the easiest way to read a file (at least for me) is using the scanner from the bufio package in the standard library. First, we need to create an instance with the NewScanner function which is a very familiar way for constructing the structs in golang. this function accepts a Reader interface as input, and the good news is os.File implemented this interface. It means, we can open a file and pass the pointer of the file to bufio.NewScanner. Let’s see it in action.

COPY

// first open the file
file, err := os.Open("/Users/Mark/fifa-winners.jsonl")
if err != nil {
    log.Fatalf("could not open the file: %v", err)
}
// don't forget to close the file.
defer file.Close()
// finally, we can have our scanner
scanner := bufio.NewScanner(file)

So, we have the scanner, we are ready to go... scanner has a function named Scan. this function moves the scanner to the next token. I'll tell you what it means but for now, let's say each time Scan called, we read one line of our file. So if we want to move the scanner all through the file, we'd call the scan function in an infinite loop! The question is How do we know, we can break the loop? It's easy! Scan returns true as the return unless it meets the end of the file.

COPY

for {
    if scanner.Scan() {
        // we have a new line in each iteration
        continue
    }
    // we are done let's break the loop
    break
}
// the rest of our spaghetti

This code works, but have you know we can say golang to keep a loop running until met a specific condition. All the code above can be as simple as the code below:

COPY

for scanner.Scan() {
    // we have a new line in each iteration
}
// the rest of our spaghetti

Well, Let's get back to the point! we can have our bytes or string in each line easily by calling Bytes() and Text() functions.

COPY

for scanner.Scan() {
  // b is an array of bytes ([]byte)
  b := scanner.Bytes()
  // s is string
  s := scanner.Text()
}

Frankly, These functions are the same! for example string(scanner.Bytes()) will give you the same result and that's what exactly happens in the Text() function.

We read our file, so is the mission completed? Not exactly, because we didn't handle any error yet.

the scanner has another function called Err(). This function gives you the first error that happened during the scan process. It means, when the scanner trying to move through the file, the Scan function returns false, if something bad happened. So our loop instantly breaks and we will out of the loop. Now we can get that error and deal with it.

If we want to know in each line of the file that error happened, we should use a traditional way, we know the scanner starts from the beginning of the file (line number 1) so we can define a variable outside of the loop that represents the line number and increase it in each iteration.

COPY

lineNumber := 0
for scanner.Scan() {
    lineNumber++
        fmt.Println(scanner.Text())
}
// the rest of our spaghetti
if err := scanner.Err(); err != nil {
    log.Fatalf("something bad happened in the line %v: %v", lineNumber, err)
}

another thing that we should consider about the Err() function is it ignores the io.EOF so if we will give an error, it's a REAL one!

Let's have a run:

COPY

? big-files (main) ? go run main.go
{"year":"2018","host":"Russia","winner":"France"}
{"year":"2014","host":"Brazil","winner":"Germany"}
{"year":"2010","host":"South Africa","winner":"Spain"}
{"year":"2006","host":"Germany","winner":"Italy"}

It worked, So what's next?

Fix bufio.Scanner: token too long error

We said, each line of a jsonl file represents a valid json, so it could be too long. We also said the Scan function moves the scanner to the next token but the question is where is the next token!?

The scanner function has another method that is not as famous as its siblings, Buffer and it needs a buffer and an integer as input and you can set the maximum size of the buffer with this function.

bufio package has a maximum token size which equals 64 * 1024 (~65.6kb). So if one line of our lines is bigger than this size, we got this error token too long error.

We found the answer to our question: The next token is where the scanner reaches max size (default 65kb) OR the end of the line.

Approach 1: Bigger buffer size

The first approach to tackling this problem is to increase the buffer size. Actually, the name bufio.MaxScanTokenSize is a little misleading because it's not the actual maximum it's THE DEFAULT MAXIMUM size. so we can increase it.

COPY

buf := []byte{}
scanner := bufio.NewScanner(file)
// increase the buffer size to 2Mb
scanner.Buffer(buf, 2048*1024)

Now we can process jsonl files with lines up to 2Mb. It's good but what if we need more? We can increase this number as much as we want (probably) but if our file has 5.000.000 rows and just one of them is 100Mb we need to increase our scanner to this size just for one line, or use another approach!

Approach2

the next way to read such a tough file! is using another function! Bufio (buffer-io) gave us way more than a simple scanner to work with files and we have to choose one of them based on our needs and requirements. in this case, Scanner cannot satisfy what we need so let's take a look at ReadLine function of bufio.Reader. It's a little bit lower level than the scanner. generally speaking, when you hear the word lower-level you should do more for simple things but you have more access and power!

So let's get started. First we need a reader:

COPY

reader := bufio.NewReader(file)

reader, has ReadLine function which tries to read the entire line. Just like the scanner, we need to call this function in a for loop but since we are at the lower level! we don't have a nice-easy boolean in return anymore to know that we can break the loop.

the other difference is the error that we will give from the ReadLine function, which can also be io.EOF. It's not going to be a real error for us, so we have to handle it too.

COPY

reader := bufio.NewReader(file)
for {
    line, _, err := reader.ReadLine()
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatalf("a real error happened here: %v\n", err)
    }
    fmt.Println(string(line))
}

As you probably already know, We just read the file so far, we did actually solve the problem that we had with the gigantic lines.

we ignore the second parameter that we gave from the ReadLine function and that one is what we exactly need to solve our problem. It's a boolean named isPrefix. If the line is too long and ReadLine cannot put all of its content in the buffer, It returns the filled buffer and set isPrefix to true which means we will give the next part of the line in the next call of the ReadLine function.

So we just need to call the ReadLine function until isPrefix becomes false then we can go for the next line of our file. You probably already noticed that we are talking about a recursive function. First I define the function that we want to call recursively.

COPY

func read(r *bufio.Reader) ([]byte, error) {
    var (
        isPrefix = true
        err      error
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }

    return ln, err
}

isPrefix is true at the first place and error is also nil so we make sure the for loop will run at least one time. It behaves like the do-while loop. We re-assign variables inside the loop so we call r.ReadLine unless we got an error OR isPrefix is false. in each iteration, we append the bytes that we get from r.ReadLine() to another variable. Now it's time to call this function inside the main function.

COPY

reader := bufio.NewReader(file)
for {
    line, err := read(reader)
    if err != nil {
        if err == io.EOF {
            break
        }
        log.Fatalf("a real error happened here: %v\n", err)
    }
    fmt.Println(string(line))
}

That's it! We solve the problem. here's the complete code:

COPY

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "os"
)

func main() {
    // first open the file
    file, err := os.Open("./fifa-winners.jsonl")
    if err != nil {
        log.Fatalf("could not open the file: %v", err)
    }
    defer file.Close()
    log.Println("******************* READ WITH SCANNER *******************")
    readWithScanner(file)
    log.Println("******************* READ WITH READLINE() *******************")

    // we just reset the offset. because we read this file once
    // imagine the cursor is in the end of the file so we have to get back to the first line and read it again 
    file.Seek(0, 0)
    readWithReadLine(file)

    log.Println("we read a file twice!")
}

// Read with simple scanner

func readWithScanner(file *os.File) {
    // first open the file
    file, err := os.Open("./fifa-winners.jsonl")
    if err != nil {
        log.Fatalf("could not open the file: %v", err)
    }
    // finally, we can have our scanner
    buf := []byte{}
    scanner := bufio.NewScanner(file)
    scanner.Buffer(buf, 2048*1024)
    lineNumber := 1
    for scanner.Scan() {
        fmt.Println(scanner.Text())
        lineNumber++
    }
    // the rest of our spaghetti
    if err := scanner.Err(); err != nil {
        log.Fatalf("something bad happened in the line %v: %v", lineNumber, err)
    }
}

// Read with Readline function

func read(r *bufio.Reader) ([]byte, error) {
    var (
        isPrefix = true
        err      error
        line, ln []byte
    )

    for isPrefix && err == nil {
        line, isPrefix, err = r.ReadLine()
        ln = append(ln, line...)
    }

    return ln, err
}

func readWithReadLine(file *os.File) {
    reader := bufio.NewReader(file)
    for {
        line, err := read(reader)
        if err != nil {
            if err == io.EOF {
                break
            }
            log.Fatalf("a real error happened here: %v\n", err)
        }
        fmt.Println(string(line))
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市迂曲,隨后出現(xiàn)的幾起案子士葫,更是在濱河造成了極大的恐慌屑那,老刑警劉巖,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件量没,死亡現(xiàn)場(chǎng)離奇詭異玉转,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)允蜈,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門冤吨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人饶套,你說我怎么就攤上這事漩蟆。” “怎么了妓蛮?”我有些...
    開封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵怠李,是天一觀的道長。 經(jīng)常有香客問我蛤克,道長捺癞,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任构挤,我火速辦了婚禮髓介,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘筋现。我一直安慰自己唐础,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開白布矾飞。 她就那樣靜靜地躺著一膨,像睡著了一般。 火紅的嫁衣襯著肌膚如雪洒沦。 梳的紋絲不亂的頭發(fā)上豹绪,一...
    開封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天,我揣著相機(jī)與錄音申眼,去河邊找鬼瞒津。 笑死蝉衣,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的巷蚪。 我是一名探鬼主播买乃,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼钓辆!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起肴焊,我...
    開封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤前联,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后娶眷,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體似嗤,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年届宠,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了烁落。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡豌注,死狀恐怖伤塌,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情轧铁,我是刑警寧澤每聪,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布,位于F島的核電站齿风,受9級(jí)特大地震影響药薯,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜救斑,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一童本、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧脸候,春花似錦穷娱、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至茶袒,卻和暖如春梯刚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背薪寓。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來泰國打工亡资, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留澜共,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓锥腻,卻偏偏與公主長得像嗦董,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子瘦黑,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容