doushou3814 2015-06-02 09:32 采纳率: 100%
浏览 195
已采纳

golang无法写入文本文件:句柄无效

Hello again everybody,

I apologize for asking another question so soon, but it just seems to be one thing after another with Go lately.

I have a working web page scraper (thanks to everybody's help) that grabs all the info I want from this wiki page: http://monsterhunter.wikia.com/wiki/MH4U:_Item_List

It then displays everything I want, no hiccups. However, when I go to write to a .txt file I get an error stating: "0 write mh4u.txt: The handle is invalid"

Here is my current code for reference:

package main

import (
    "fmt"
    "log"

    "github.com/PuerkitoBio/goquery"
    "os"
    "io"
)

func main() {

    filename := "mh4u.txt"
    file, err := os.Create(filename)

    if err!= nil {
        fmt.Println(err)
    }
    doc, err := goquery.NewDocument("http://www.ign.com/wikis/monster-hunter-4/Items")
    if err != nil {
        log.Fatal(err)
    }

    doc.Find("tbody").Each(func(i int, s *goquery.Selection) {

        s.Find("td").Each(func(j int, s2 *goquery.Selection) {

            if s3 := s2.Find("img"); s3 != nil && s3.Length() > 0 {
                return
            }

            fmt.Printf(s2.Text())
            n, err := io.WriteString(file, s2.Text())

            if err != nil {
                fmt.Println(n, err) 
            }
        })

        file.Close()
    })
}

Testing this code with other web sites leads me to believe that there is maybe some hidden characters that is giving the writer some issues, but that's the only thing I can guess.

Thanks so much for any suggestions/tips/solutions you can offer!

  • 写回答

1条回答 默认 最新

  • dongsuichi6529 2015-06-02 09:39
    关注

    You're calling file.Close() inside a closure. If doc.Find("tbody").Each is called more than one time, you'll end up trying to write to a closed file. You should defer the file closing right after you've created it:

    file, err := os.Create(filename)
    if err != nil {
        log.Fatal(err)
    }
    defer file.Close()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?