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

时间:2013-11-23 13:19:06

标签: python python-2.7 matplotlib temporary-files

我正在尝试将我的数字保存在临时文件中。我想以最蟒蛇的方式做到这一点。为此,我尝试使用tempfile,但我遇到了一些问题。 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的全部意义已经消失,因为我必须自己处理命名和删除tempfile,因为我必须打开它两次。有什么方法可以使用tempfile(没有奇怪的解决方法/黑客攻击)?

1 个答案:

答案 0 :(得分:7)

文件具有执行读取,写入的当前位置。最初文件位置在开头(除非您使用追加移动(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())