Python - open file in paint with whitespaces

I am trying to open an image in paint with python, however, the path contains a space, paint throws an error saying it cannot find the path because it has just split the string until the first space. Can someone tell me how to solve this without changing the path? Here is my code:

import subprocess, os

paintImage = "C:\\Users\\Me\MY Images\\image.png"

#get the path of paint:
paintPath = os.path.splitdrive(os.path.expanduser("~"))[0]+r"\WINDOWS\system32\mspaint.exe"
#open the file with paint
subprocess.Popen("%s %s" % (paintPath, paintImage))

However, paint opens and says that C:\Users\Me\MY contains an invalid path, because it has not counted the space. I have tried replacing the space with %20, but that does not work.

Thanks

Hi @elenaflorence

Welcome to the Knime Community.

Usually when you want have a space in a directory or filename and want to use this from a commandline you have to add double quotes around this name in order to get it working.

So your command would have to be on a commandline like:
C:\WINDOWS\system32\mspaint.exe “C:\Users\Me\My Images\image.png”

You have to mimic this in your subprocess. I haven’t tried it but I would assume the following works:
subprocess.Popen('%s "%s"' % (paintPath, paintImage))

1 Like