当我的数据文件如下所示时,如何从Google Go中的文件中读取数据:
SomeString 200.0 2
OtherString 100.6 9
OneMoreString 550.8 1
(String,double和integer)。我尝试了bufio.readLine
和bufio.readString
,但这些都是读取整行,而我需要分离的变量。
答案 0 :(得分:4)
这样的事情可能有用 - 如果你的字符串中有空格,你可能需要以不同的方式处理:
package main
import (
"fmt"
"os"
)
func main() {
f, err := os.Open("scan.txt")
if err != nil {
fmt.Println(err)
}
for {
var i int
var flt float64
var str string
var n int
n, err = fmt.Fscanln(f, &str, &flt, &i)
if n == 0 || err != nil {
break
}
fmt.Println("string:", str, "; float:", flt, "; int:", i)
}
}
输出:
string: SomeString ; float: 200 ; int: 2
string: OtherString ; float: 100.6 ; int: 9
string: OneMoreString ; float: 550.8 ; int: 1
答案 1 :(得分:0)
例如,
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type Data struct {
AString string
AFloat float64
AnInt int64
}
func ParseLine(line string) (*Data, error) {
data := new(Data)
var err error
text := strings.TrimRight(line, " ")
i := strings.LastIndex(text, " ")
i++
text = text[i:]
data.AnInt, err = strconv.ParseInt(text, 10, 64)
if err != nil {
return nil, err
}
line = line[:i]
text = strings.TrimRight(line, " ")
i = strings.LastIndex(text, " ")
i++
text = text[i:]
data.AFloat, err = strconv.ParseFloat(text, 64)
if err != nil {
return nil, err
}
line = line[:i]
data.AString = line
return data, nil
}
func main() {
f, err := os.Open("data.txt")
if err != nil {
fmt.Fprintln(os.Stderr, "opening input:", err)
return
}
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
data, err := ParseLine(line)
if err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err, ":", line)
continue
}
fmt.Println(*data)
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "reading input:", err)
}
}
输入(data.txt):
Some String 200.0 2
Other String 100.6 9
One More String 550.8 1
输出:
{Some String 200 2}
{Other String 100.6 9}
{One More String 550.8 1}