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

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

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函数等等...

任何帮助将不胜感激。

以下是我目前的代码:

  1. package main
  2. import "fmt"
  3. import "io/ioutil"
  4. func main() {
  5. fmt.Println(ioutil.ReadFile("one-hundred_50.txt"))
  6. }
英文:

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:

  1. package main
  2. import &quot;fmt&quot;
  3. import &quot;io/ioutil&quot;
  4. func main() {
  5. fmt.Println(ioutil.ReadFile(&quot;one-hundred_50.txt&quot;))
  6. }

答案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

  1. package main
  2. import (
  3. "os"
  4. "bufio"
  5. "fmt"
  6. )
  7. func main() {
  8. r := bufio.NewReader(os.Stdin)
  9. line, err := r.ReadString('\n')
  10. for i := 1; err == nil; i++ {
  11. fmt.Printf("第%d行:%s", i, line)
  12. line, err = r.ReadString('\n')
  13. }
  14. }

使用方法:

  1. 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:

  1. package main
  2. import (
  3. &quot;os&quot;
  4. &quot;bufio&quot;
  5. &quot;fmt&quot;
  6. )
  7. func main() {
  8. r := bufio.NewReader(os.Stdin)
  9. line, err := r.ReadString(&#39;\n&#39;)
  10. for i := 1; err == nil; i++ {
  11. fmt.Printf(&quot;Line %d: %s&quot;, i, line)
  12. line, err = r.ReadString(&#39;\n&#39;)
  13. }
  14. }

To use:

  1. go run solution.go &lt; inputfile

答案3

得分: 0

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

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

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

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:

  1. func main() {
  2. f, e := os.Open(&quot;one-hundred_50.txt&quot;)
  3. if e != nil {
  4. // error opening file, handle it
  5. }
  6. s := bufio.NewScanner(f)
  7. for s.Scan() {
  8. // scanner.Text() contains the current line
  9. }
  10. if e = s.Err(); e != nil {
  11. // error while scanning; no error at EOF
  12. }
  13. }

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:

确定