python - 将 svg 保存到临时文件 Python

标签 python django svg temporary-files

我正在使用创建 .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()

任何人都可以解释为什么这不起作用和/或我如何在不创建文件的情况下做到这一点(我只需要稍后删除)。 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()

关于python - 将 svg 保存到临时文件 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31433219/

相关文章:

python - Flask/Jinja 列表中的下拉菜单

django - Django 的 select_for_update 在同一条记录上使用两次时会死锁吗?

html - Svg 数字 - 需要缩放和翻译,Chrome 和 Firefox 之间的区别

svg - 在 ipython 中使用 igraph 绘制顶点标签的问题

javascript - Raphael javascript 中的偏移量在哪里

python - 在 python 中绘制 sympy 结果

python - 用于数据库驱动程序的Gevent/Eventlet猴子修补

python - 围绕 python 最有趣的项目是什么?

javascript - 如何在 Django 中检测浏览器的关闭?

python - Django 和 docker : outputting information to console