When I try to save a matplotlib figure in Spyder, which is running in Windows 10, there is an error. My code is very simple, it looks like:
date0 = datetime(2018, 1, 1, 0, 0)
m.contourf(x, y, Zp * norm_vert, np.arange(0, 40, 0.1), cmap = 'jet')
plt.colorbar(cmap = 'jet')
plt.savefig("C:\\Work\\IWV\\" + str(date0) + ".png")
and the error is:
OSError: [Errno 22] Invalid argument: 'C:\\Work\\IWV\\2018-01-01 00:00:00.png'
I also tried to rewrite the last line as:
plt.savefig(r"C:\Work\IWV\" + str(date0) + ".png")
but in this case the entire argument of savefig is considered as a string, so the name of the file will be something like "str(date0) + .png.png". Is anyone can help me to solve this issue?
You're getting an error because you can't name a file with the symbol :
. Instead of str(date0)
, use this:
date0.strftime("%B-%d-%Y-%H-%M-%S")
You will have a string that can be saved, without the forbidden character :
, like this:
Out[11]: 'January-01-2018-00-00-00'
Or any other format you prefer. Read more about strftime
here . You'll then be able to + '.png'
for the file extension.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.