登录
首页 >  Golang >  Go问答

使用Go语言读取文本文件并提取信息

来源:stackoverflow

时间:2024-02-18 15:21:23 482浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用Go语言读取文本文件并提取信息》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我有一个txt文件,在这个文件中我只需要int值,我怎样才能得到这个值?

txt 文件 - ->04-06-2021 20:21:59 时利润 = 10

我使用此代码获取此文件..!

func Profit() string {
    TargetClosePrice := 110
    ontickerPrice := 100
    Time := time.Now()
    totalProfit := TargetClosePrice - ontickerPrice
    str := strconv.Itoa(totalProfit)
    value := `Profit = ` + str + ` at the Time of ->` + Time.Format("01-02-2006 15:04:05") + "\n"

    data, err := os.OpenFile("Profit.txt", os.O_APPEND, 0644)
    if err != nil {
        log.Fatal("whoops", err)
    }
    io.Copy(data, strings.NewReader(value))
    return str
}

但现在我只需要 txt 文件中的 10 个..?我怎样才能得到?


正确答案


我认为这符合你的要求:

package main

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

func main() {
   f, e := os.Open("Profit.txt")
   if e != nil {
      panic(e)
   }
   defer f.Close()
   s := bufio.NewScanner(f)
   for s.Scan() {
      var n int
      fmt.Sscanf(s.Text(), "Profit = %v", &n)
      fmt.Println(n)
   }
}

https://golang.org/pkg/fmt#Scanf

终于介绍完啦!小伙伴们,这篇关于《使用Go语言读取文本文件并提取信息》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>