将 svg 保存到临时文件 Python

Save svg to tempfile Python

我正在使用创建 .svg 的第 3 方 python 库(专​​门用于进化树),它具有树对象的 render 函数。我想要的是我可以编辑的字符串形式的 svg 。目前我保存 svg 并按如下方式读取文件:

tree.render('location/filename.svg', other_args...)
f = open('location/filename.svg', "r")
svg_string = f.read()
f.close()

这可行,但是否可以改用临时文件?到目前为止我有:

t = tempfile.NamedTemporaryFile()
tmpdir = tempfile.mkdtemp()
t.name = os.path.join(tmpdir, 'tmp.svg')
tree.render(t.name, other_args...)
svg_string = t.read()
t.close()

任何人都可以解释为什么这不起作用 and/or 我如何在不创建文件的情况下做到这一点(我只需要稍后删除)。 svg_string 我继续编辑以在 django 应用程序中使用。

编辑: 重要的是,渲染函数也可用于创建其他文件类型,例如.png - 因此需要指定 .svg 扩展名。

您不应该自己定义临时文件的名称。创建它时,名称将随机生成。可以直接使用。

t = tempfile.NamedTemporaryFile()
tree.render(t.name, other_args...)
t.file.seek(0) #reset the file pointer to the beginning
svg_string = t.read()
t.close()