I have a turtle program that creates an image. I have the following code to save the canvas as svg. (I don't include the turtle program here).
import os
import tempfile
import shutil
name = input("What would you like to name it? \n")
nameSav = name + ".png"
tmpdir = tempfile.mkdtemp() # create a temporary directory
tmpfile = os.path.join(tempdir, 'tmp.svg') # name of file to save SVG to
ts = turtle.getscreen().getcanvas()
canvasvg.saveall(tmpfile, ts)
with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output:
cairosvg.svg2png(bytestring=svg_input.read(), write_to=png_output)
shutil.rmtree(tmpdir) # clean up temp file(s)
This works in IDLE. The canvas is saved as a png just fine. If I run it with the Python Launcher for Windows, I get:
with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output:
PermissionError: [Errno 13] Permission denied: 'test.png'
test.png is the name I chose at this point when I saved (ie, NameSav). So what's up with this? Why doesn't IDLE get this error? How can I fix it?
The error means that permission is denied in saving test.png
in the current working directory of the Python launcher, which would be the location of the launcher exe. Give the input prompt a full path, like C:\Users\Spam\Documents\test.png
, or use os.path.join
to prepend an appropriate directory in front of nameSav
.
Why IDLE works is that IDLE has a different current working directory, that pointing to a folder where writes are allowed.
Say, you want to save the resulting image to the images
subfolder of the folder containing your script, you can calculate the target file name as
from os import path
filename = input("What would you like to name it? \n")
if not filename.lower().endswith('.png'):
filename += '.png'
target_path = path.join(path.abspath(path.dirname(__file__)), 'images', filename)
with ... open(target_path, 'wb') as png_output:
...