On Windows, fig.savefig() can’t overwrite existing file when it is already open (OSError: [Errno 22] Invalid argument)

  locking, matplotlib, python, windows

I have some process that computes things, and every now and then, I save a graph on the disk. It’s useful to keep the file opened to look at the early results as the process is running.

On Ubuntu, the image is simply updated whenever a new version of the graph is saved. However on Windows, the call fig.savefig(<filename>) returns an error if there already exists a file of the same name and that the file is opened (if the file is not opened then it just overwrites the already existing one without issue).

The error is:

OSError: [Errno 22] Invalid argument

Here is a minimal example: to get the error, run this and open the file myplot.png

import matplotlib.pyplot as plt
import math
import time

x = []
y = []

for t in range(100):
    if t % 5 == 0:
        fig, ax = plt.subplots(1, 1)
        ax.plot(x, y)

I guess it would have to do with the image-viewer on Windows locking the file? Anyone knows a fix?

Source: Windows Questions