Escape (‘\’) your “\” (backslash) characters when Python writes paths for Windows…

When using Python to prepare strings For Windows, always escape ‘\’ your “\” (backslash) characters in a path name. So ‘\\’ everywhere. It looks like a double ‘\’ but the first one is really “escape” and the second character is interpreted as a literal, not, in this case, as ‘escape’…

What am I talking about??

If your Python program will create file path names for Windows computers, you need to be extra thoughtful as you enter string constants for them.

For example, consider the string "blather\pather\gather"
Give that to the Python Interpreter, and it will show you how it is understood by Python:

>>> "blather\pather\gather"

See what happedened to “blather\pather\gather”?
Python put an escape back slash before each of the (presumably) literal back slashes. Its easy to see if you line them up:


The string delimiters have changed too- python gives ‘ and ” the same meaning, defaults to ‘ and requires them to be used in pairs. ” is an empty string, “” is an empty string, ‘” opens a quoted string inside a quoted string. Better not close it backwards: “”” is an empty string. “‘”‘ is missing a close “.

So far, so good. You might think Python will understand back slashes in things you identify as strings and respect them. That’s nice.

Change the string to

What’s that?? Turns out that Python recognizes “\r” as (carriage return), “\n” a newline and “\t” as a tab. And \a as (control)a, with is slightly startling. But not \G or \g as “bell”…

So they’re compound characters, and they get issued without escapes being added. Why? I don’t know. But I do know that putting an excape backslash before the delimiter backslash results in the text being left alone, and written out exactly the same. And when it goes to Windows, Windows strips off the first backslash and correctly interprets the second one.

Here’s an advantage for Python, as my friend James points out. You can just look at what it does and how it sees things. The realization I’m reporting started wth a Python script trying to call a Windows .bat script… it worked well for some .bat scripts and didn’t work for others. ?!?!?!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s