This is a language feature that is so common on Unix that Unix programmers never think twice about it. Certainly, a Unix programmer would never consider it to be a gotcha. But for someone coming from a Windows background, it may very well be unfamiliar.
The gotcha may occur when you try to code a Windows filename like this:
myFilename = "c:\newproject\typenames.txt" myFile = open(myFilename, "r")
and — even though the input file exists — when you run your program, you get the error message
IOError: [Errno 2] No such file or directory: 'c:\newproject\typenames.txt'
To find out what’s going on, you put in some debugging code:
myFilename = "c:\newproject\typenames.txt" print "(" + myFilename + ")"
And what you see printed on the console is:
(c: ewproject ypenames.txt)
What has happened is that you forgot that in Python (as in most languages that evolved in a Unix environment) in quoted string literals the backslash has the magical power of an escape character. This means that a backslash isn’t interpreted as a backslash, but as a signal that the next character is to be given a special interpretation. So when you coded
myFilename = "c:\newproject\typenames.txt"
the “\n” that begins “\newproject” was interpreted as the newline character, and the “\t” that begins “\typenames.txt” was interpreted as the tab character. That’s why, when you printed the filename, you got the result that you did. And it is why Python couldn’t find your file — because no file with the name
could be found.To put a backslash into a string, you need to code two backslashes — that is, the escape character followed by a backslash. So to get the filename that you wanted, you needed to code
myFilename = "c:\\newproject\\typenames.txt"
And under some circumstances, if Python prints information to the console, you will see the two backslashes rather than one. For example, this is part of the difference between the repr() function and the str() function.
myFilename = "c:\\newproject\\typenames.txt" print repr(myFilename), str(myFilename)
Escape characters are documented in the Python Language Reference Manual. If they are new to you, you will find them disconcerting for a while, but you will gradually grow to appreciate their power.