doufunuo4787 2018-07-20 20:02
浏览 13
已采纳

os.Create“打开的文件太多”

I have around 220'000 image files (.png) to create. I run into this error message when trying to create the 1'081th file: panic: open /media/Snaps/pics/image1081_0.png: too many open files

I've added the defer w.Close() line but it did not change the error.

    i := 1
    for i <= 223129 {

    (some other code to prepare the data and create the chart)

    img := vgimg.New(450, 600)
    dc := draw.New(img)

    canvases := table.Align(plots, dc)
    plots[0][0].Draw(canvases[0][0])
    plots[1][0].Draw(canvases[1][0])
    plots[2][0].Draw(canvases[2][0])


    testFile := "/media/Snaps/pics/image"+strconv.Itoa(i+60)+"_"+gain_loss+".png"

        w, err := os.Create(testFile)
        if err != nil {
            panic(err)
        }
        defer w.Close()

        png := vgimg.PngCanvas{Canvas: img}
        if _, err := png.WriteTo(w); err != nil {
            panic(err)
        }   

        //move to next image
        i = i + 1
     }

Surely this limit can be worked around ? Maybe I'm not closing the files properly ?

  • 写回答

3条回答 默认 最新

  • du8589840 2018-07-20 20:43
    关注

    ok, i got it, changed defer w.Close() to w.Close() and moved it after

    png := vgimg.PngCanvas{Canvas: img}
    if _, err := png.WriteTo(w); err != nil {
          panic(err)
    }
    

    I'm now above 10'000 images and running...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?