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.
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)) } }
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]) } }
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!