使用Python Launcher保存图片时出现权限错误ERRNO13,而不是IDLE -- Python
我有一个海龟程序,可以创建图像。我有以下代码可以把画布保存为svg格式。(这里不包括海龟程序的部分)
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)
在IDLE中运行这个代码是没问题的,画布可以顺利保存为png格式。如果我用Windows的Python启动器来运行,就出现了:
with open(tmpfile) as svg_input, open(nameSav, 'wb') as png_output:
PermissionError: [Errno 13] Permission denied: 'test.png'
test.png是我在保存时选择的文件名(也就是NameSav)。那么这是怎么回事呢?为什么在IDLE中没有这个错误?我该怎么解决这个问题呢?
1 个回答
1
这个错误的意思是,Python 启动器在当前工作目录中保存 test.png
时没有权限。当前工作目录就是启动器程序所在的位置。你可以给输入提示一个完整的路径,比如 C:\Users\Spam\Documents\test.png
,或者使用 os.path.join
在 nameSav
前面加上一个合适的目录。
IDLE 能正常工作是因为它的当前工作目录不同,指向一个允许写入的文件夹。
比如,你想把生成的图片保存到包含你脚本的文件夹中的 images
子文件夹里,你可以这样计算目标文件名:
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:
...