【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

    }

详细讲解:https://devmarkpro.com/working-big-files-golang


转载:
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))
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,547评论 6 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,399评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,428评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,599评论 1 274
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,612评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,577评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,941评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,603评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,852评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,605评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,693评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,375评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,955评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,936评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,172评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,970评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,414评论 2 342

推荐阅读更多精彩内容