在Go编程语言中读取和处理外部文件

huangapple go评论87阅读模式
英文:

Reading and working with an external file in the Go programming language

问题

我一直通过解决一些欧拉项目的问题来学习Go编程语言。我现在正在解决[问题13](http://projecteuler.net/problem=13)。它包含一个包含100行50位数字的外部文件。我的问题是:如何将这个文件读入Go程序并进行处理?Go语言有一个readlines函数吗?我已经阅读了关于io和ioutil包的资料,我能想到的就是读取文件并打印它;然而,我不确定如何处理这个文件...它可以赋值给一个变量吗?是否有readlines函数等等...

任何帮助将不胜感激。

以下是我目前的代码:

package main

import "fmt"
import "io/ioutil"

func main() {
    fmt.Println(ioutil.ReadFile("one-hundred_50.txt"))
}
英文:

I have been learning the Go programming language by doing some of the Project Euler problems. I am now on [problem 13] (<http://projecteuler.net/problem=13>). It contains an external file with 100 lines of 50 digit numbers. My question is: How can this file be read into a Go program and worked with? Does Go have a readlines function? I've read about the io and ioutil packages, and about all I can come up with is reading in the file and printing it; however, I am not sure how to work with the file... Can it be assigned to a variable? Is there a readlines function, etc...

Any help would be appreaciated.

Here is what I have so far:

package main

import &quot;fmt&quot;
import &quot;io/ioutil&quot;

func main() {
	    fmt.Println(ioutil.ReadFile(&quot;one-hundred_50.txt&quot;))
}

答案1

得分: 3

有方法可以逐行读取文件(如果在这里搜索,会有示例),但是真正的ioutil.ReadFile是一个很好的开始。当然你可以将它赋值给一个变量。看一下ReadFile的函数签名,看看它是如何同时返回一个字节切片和一个错误的。同时赋值;检查错误是否为nil。如果不是nil,则打印错误,以便查看出了什么问题。然后,一旦你将字节存储在一个变量中,尝试按行分割它。尝试使用bytes.Split,或者更简单地将其转换为字符串并使用strings.Split。

英文:

There are ways to read a file line by line (and there are examples if you search here on SO) but really ioutil.ReadFile is a good start there. Sure you can assign it to a variable. Look at the function signature for ReadFile and see how it returns both a byte slice and an error. Assign both; check that the error is nil. Print the error if it's not nil so you can see what's wrong. Then once you have the bytes in a variable, try spitting it up by lines. Try bytes.Split, or easier, convert it to a string and use strings.Split.

答案2

得分: 1

请查看bufio这个答案使用它将整个文件读入内存。

对于这个欧拉问题,你可以使用ReadString

package main

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

func main() {
  r := bufio.NewReader(os.Stdin)
  line, err := r.ReadString('\n')
  for i := 1; err == nil; i++ {
    fmt.Printf("第%d行:%s", i, line)
    line, err = r.ReadString('\n')
  }
}

使用方法:

go run solution.go < inputfile
英文:

Check out bufio. This answer uses it to read the entire file into memory.

For this Euler problem you can just use ReadString:

package main

import (
  &quot;os&quot;
  &quot;bufio&quot;
  &quot;fmt&quot;
)

func main() {
  r := bufio.NewReader(os.Stdin)
  line, err := r.ReadString(&#39;\n&#39;)
  for i := 1; err == nil; i++ {
    fmt.Printf(&quot;Line %d: %s&quot;, i, line)
    line, err = r.ReadString(&#39;\n&#39;)
  }
}

To use:

go run solution.go &lt; inputfile

答案3

得分: 0

自从这个问题被提出和回答之后,bufio包已经更新(适用于Go 1.1),现在可能有更好的解决方案可用(尽管这些解决方案都不错)。

bufio包中的Scanner类型使得这个问题变得非常简单:

func main() {
    f, e := os.Open("one-hundred_50.txt")
    if e != nil {
        // 处理打开文件时的错误
    }
    s := bufio.NewScanner(f)
    for s.Scan() {
        // scanner.Text() 包含当前行的内容
    }
    if e = s.Err(); e != nil {
        // 扫描时出错;在EOF时没有错误
    }
}
英文:

Since this question was asked and answered the bufio package has been updated (for Go 1.1) and perhaps a nicer solution is now available (not that any of these are bad).

The Scanner type from the bufio package makes this really easy:

func main() {
    f, e := os.Open(&quot;one-hundred_50.txt&quot;)
    if e != nil {
        // error opening file, handle it
    }
    s := bufio.NewScanner(f)
    for s.Scan() {
        // scanner.Text() contains the current line
    }
    if e = s.Err(); e != nil {
        // error while scanning; no error at EOF
    }
}

huangapple
  • 本文由 发表于 2012年5月25日 06:28:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/10746184.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定