我目前在 Windows (10) 上保存 matplotlib 图形时遇到了一些困难。我知道需要使用原始字符串,但即使使用这些字符串并确保路径正确,也会引发 FileNotFoundError 。我也尝试过 os.path.normpath 但这也很顺利。以下是相关行:
fig, ax = plt.subplots()
ax.plot(sin_i, sin_r, label='acrylic glass')
ax.plot(sin_i, sin_r_wtr, label='water')
ax.legend()
ax.set(xlabel=r'$sin(\alpha_{refracted})$', ylabel=r'$sin(\alpha_{incident})$',
title=r'$f([sin(\alpha_{refracted}])$ for acrylic glass and water')
ax.grid()
#fig.savefig(r"c:\Users\julie\Pictures\PY3graph.png")
fig.savefig(os.path.normpath("c:/Users/julie/Pictures/PY3graph.png"))
和错误:
Traceback (most recent call last):
File "PY_3_graphs.py", line 31, in <module>
fig.savefig(r"PY_3_graph.png")
File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\figure.py", line 2094, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\backend_bases.py", line 2075, in print_figure
**kwargs)
File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\backends\backend_agg.py", line 521, in print_png
cbook.open_file_cm(filename_or_obj, "wb") as fh:
File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\contextlib.py", line 112, in __enter__
return next(self.gen)
File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\cbook\__init__.py", line 407, in open_file_cm
fh, opened = to_filehandle(path_or_file, mode, True, encoding)
File "C:\Users\julie\AppData\Local\Programs\Python\Python37-32\lib\site-packages\matplotlib\cbook\__init__.py", line 392, in to_filehandle
fh = open(fname, flag, encoding=encoding)
FileNotFoundError: [Errno 2] No such file or directory: 'c:\\Users\\julie\\Pictures\\PY3graph.png'
尝试通过 plt.show() 保存图形也会返回“没有这样的文件或目录”错误。
我会非常感谢你的帮助!
马特
更新:该代码在保存在辅助硬盘驱动器(例如 d:\ )上时有效,但不在 c:\ 上。我怀疑是权限错误,但即使授予管理员对命令提示符的权限,问题仍然存在。
更新2:我终于弄清楚了原因是什么。Fall Creators Update 中出现的新的“受控文件夹访问”功能似乎是问题的根源,然后可以通过解锁受保护的文件夹轻松解决。