python - matplotlib 的 savefig() 不能使用读写文件?

标签 python python-2.7 matplotlib temporary-files

我正在尝试将我的图形保存在临时文件中。我想以最 pythonic 的方式来做。为此,我尝试使用临时文件,但遇到了一些问题。 savefig 函数应该能够将文件名作为字符串或类似文件的对象,在我尝试的前两件事中我完全没有看到违反。

这是我最初尝试的:

with tempfile.TemporaryFile(suffix=".png") as tmpfile:
    fig.savefig(tmpfile, format="png") #NO ERROR
    print b64encode(tmpfile.read()) #NOTHING IN HERE

然后我尝试了什么:

with open("test.png", "rwb") as tmpfile:
    fig.savefig(tmpfile, format="png")
    #"libpngerror", and a traceback to 
    # "backends_agg.py": "RuntimeError: Error building image"
    print b64encode(tmpfile.read()) 

然后我尝试了什么:

with open("test.png", "wb") as tmpfile:
    fig.savefig(tmpfile, format="png")

with open("test.png"), "rb") as tmpfile:
    print b64encode(tmpfile.read())

这行得通。但是现在使用模块 tempfile 的全部意义都没有了,因为我必须自己处理命名和删除临时文件,因为我必须打开它两次。有什么方法可以使用临时文件(没有奇怪的解决方法/黑客)?

最佳答案

文件具有执行读、写的当前位置。最初文件位置在开头(除非您使用追加移动 (a) 打开文件或您显式移动文件位置)。

如果您相应地写入/读取,文件位置会提前。如果不倒带文件,则从那里读取时将得到空字符串。使用file.seek , 可以移动文件位置。

with tempfile.TemporaryFile(suffix=".png") as tmpfile:
    fig.savefig(tmpfile, format="png") # File position is at the end of the file.
    tmpfile.seek(0) # Rewind the file. (0: the beginning of the file)
    print b64encode(tmpfile.read())

关于python - matplotlib 的 savefig() 不能使用读写文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20162802/

相关文章:

python - 从不同的程序访问字典

python - 如何使用 Matplotlib 对 Pandas 数据框中的数据进行分类和绘图?

python - 如何正确制作我自己的模块以在其中导入另一个模块?

python - 在 IPython Notebook 中绘制多个子图

python - pyqt 中使用 matplotlib 绘制对数图 - 轴消失

python - 给定词典索引查找多集排列的算法

python - Pygame "No module called pygame.base"

python - 如何处理已安装模块的方法的轻微更改?

python - 从颜色图中获取 "n"数字的 "n"等间距 RGB 颜色

python - Python 2 和 Python 3 中 exec 函数的行为