Python path and raw strings

Math_reald picture Math_reald · Aug 3, 2016 · Viewed 18.6k times · Source

I have some problems with the name of path + file (which is an input for a function). This works:

result=r"D:\final\Res.mat"

This does not work:

result="D:\\final\\Res.mat"

What I would like to do is the following (but also does not work [Errno 22] invalid mode ('rb') or filename:):

path = "D:\final"
nameFile= "Res"

result=''+ path+ '\\' + nameFile'mat'+''

How do I get the "r" in front of the name without using " "? Or, is there a possibility without putting r in front of the path?

Answer

holdenweb picture holdenweb · Aug 3, 2016

My interpreter suggests that you are mistaken in your belief that the second example does not work, because

>>> r"D:\final\Res.mat" == "D:\\final\\Res.mat"
True

The correct way to build file paths from components is by using the os.path.join function, which can take multiple arguments and is portable across platforms. I would suggest you try something like

result = os.path.join(path, nameFile+".mat")