逐行读取文件

  • Post author:
  • Post category:其他


本文翻译自:

reading file line by line in go


I’m unable to find

file.ReadLine

function in Go.


我在Go中找不到

file.ReadLine

函数。


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?


如何逐行读取文件?


#1楼

参考:

https://stackoom.com/question/AKcd/逐行读取文件


#2楼


EDIT: As of go1.1, the idiomatic solution is to use

bufio.Scanner



编辑:从go1.1开始,惯用的解决方案是使用

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.


Readln(* bufio.Reader)函数从基础bufio.Reader结构返回一行(sans \\ n)。

// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
  var (isPrefix bool = true
       err error = nil
       line, ln []byte
      )
  for isPrefix && err == nil {
      line, isPrefix, err = r.ReadLine()
      ln = append(ln, line...)
  }
  return string(ln),err
}


You can use Readln to read every line from a file.


您可以使用Readln读取文件中的每一行。


The following code reads every line in a file and outputs each line to stdout.


以下代码读取文件中的每一行,并将每一行输出到stdout。

f, err := os.Open(fi)
if err != nil {
    fmt.Printf("error opening file: %v\n",err)
    os.Exit(1)
}
r := bufio.NewReader(f)
s, e := Readln(r)
for e == nil {
    fmt.Println(s)
    s,e = Readln(r)
}


Cheers!


干杯!


#3楼



bufio.Reader.ReadLine()

works well.



bufio.Reader.ReadLine()

运作良好。


But if you want to read each line by a string, try to use

ReadString(‘\\n’)

.


但是,如果

要按

字符串读取每一行,请尝试使用

ReadString(’\\ n’)




It doesn’t need to reinvent the wheel.


不需要重新发明轮子。


#4楼


You can also use ReadString with \\n as a separator:


您还可以使用带有\\ n的ReadString作为分隔符:

  f, err := os.Open(filename)
  if err != nil {
    fmt.Println("error opening file ", err)
    os.Exit(1)
  }
  defer f.Close()
  r := bufio.NewReader(f)
  for {
    path, err := r.ReadString(10) // 0x0A separator = newline
    if err == io.EOF {
      // do something here
      break
    } else if err != nil {
      return err // if you return error
    }
  }

#5楼

// strip '\n' or read until EOF, return error if read error  
func readline(reader io.Reader) (line []byte, err error) {   
    line = make([]byte, 0, 100)                              
    for {                                                    
        b := make([]byte, 1)                                 
        n, er := reader.Read(b)                              
        if n > 0 {                                           
            c := b[0]                                        
            if c == '\n' { // end of line                    
                break                                        
            }                                                
            line = append(line, c)                           
        }                                                    
        if er != nil {                                       
            err = er                                         
            return                                           
        }                                                    
    }                                                        
    return                                                   
}                                    

#6楼


In Go 1.1 and newer the most simple way to do this is with a


bufio.Scanner


.


在Go 1.1和更高版本中,最简单的方法是使用


bufio.Scanner





Here is a simple example that reads lines from a file:


这是一个从文件读取行的简单示例:

package main

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

func main() {
    file, err := os.Open("/path/to/file.txt")
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()

    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        fmt.Println(scanner.Text())
    }

    if err := scanner.Err(); err != nil {
        log.Fatal(err)
    }
}


This is the cleanest way to read from a

Reader

line by line.


这是逐行从

Reader

读取的最干净的方法。


There is one caveat: Scanner does not deal well with lines longer than 65536 characters.


请注意以下几点:扫描程序不能处理超过65536个字符的行。


If that is an issue for you then then you should probably roll your own on top of

Reader.Read()

.


如果这对您来说是个问题,那么您可能应该将自己的代码放在

Reader.Read()

之上。