Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save svg to tempfile Python

I am using a 3rd party python library that creates .svg's (specifically for evolutionary trees) which has a render function for tree objects. What I want is the svg in string form that I can edit. Currently I save the svg and read the file as follows:

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

This works, but is it possible to use a tempfile instead? So far I have:

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()

Can anyone explain why this doesn't work and/or how I could do this without creating a file (which I just have to delete later). The svg_string I go on to edit for use in a django application.

EDIT: Importantly, the render function can also be used to create other filetypes e.g. .png - so the .svg extension needs to be specified.

like image 959
edc505 Avatar asked Dec 30 '25 10:12

edc505


1 Answers

You should not define yourself the name of your temporary file. When you create it, the name will be randomly generated. You can use it directly.

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()
like image 61
Patrick Avatar answered Jan 01 '26 23:01

Patrick