How to read file with custom delimiter in Golang?

WBOY
Release: 2024-06-05 15:22:41
Original
760 people have browsed it

Read files using custom delimiters in Golang: Use bufio.NewReader to create a Reader object. Set up the reader.SplitFunc function to return the position and line of the custom separator. Read the file in a loop and process it line by line.

如何在 Golang 中使用自定义分隔符读取文件?

How to use custom delimiters to read files in Golang

When reading files in Golang, the default delimiter character is a newline character. However, sometimes we may need to use custom delimiters to read files. This article explains how to read files using custom delimiters.

Code example

package main

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

func main() {
    // 打开文件以进行读取
    file, err := os.Open("data.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // 使用自定义分隔符创建 bufio.Reader 对象
    reader := bufio.NewReader(file)
    reader.SplitFunc = func(data []byte, atEOF bool) (int, []byte, error) {
        // 返回自定义分隔符的位置
        delimIndex := bytes.IndexByte(data, ';') // 假设分隔符是分号(;)

        if delimIndex == -1 {
            // 如果没有找到分隔符,则返回当前行的剩余部分
            return len(data), data, nil
        }

        // 返回分隔符的位置和分隔符之前的行
        return delimIndex + 1, data[:delimIndex], nil
    }

    // 逐行读取文件
    for {
        line, _, err := reader.ReadLine()
        if err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }

        // 处理每行
        fmt.Println(string(line))
    }
}
Copy after login

Practical case

The following is a code example for reading a CSV file using semicolon delimiters :

package main

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

func main() {
    // 打开 CSV 文件
    file, err := os.Open("customers.csv")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    // 使用分号分隔符创建 bufio.Reader 对象
    reader := bufio.NewReader(file)
    reader.SplitFunc = func(data []byte, atEOF bool) (int, []byte, error) {
        delimIndex := bytes.IndexByte(data, ';')
        if delimIndex == -1 {
            return len(data), data, nil
        }

        return delimIndex + 1, data[:delimIndex], nil
    }

    // 逐行读取 CSV 文件
    for {
        line, _, err := reader.ReadLine()
        if err == io.EOF {
            break
        } else if err != nil {
            log.Fatal(err)
        }

        // 根据分隔符拆分每一行
        parts := bytes.Split(line, []byte(";"))

        // 处理每一行
        fmt.Printf("ID: %s, Name: %s, Email: %s\n", parts[0], parts[1], parts[2])
    }
}
Copy after login

The above is the detailed content of How to read file with custom delimiter in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template