What's the Scoop on \\ for Paths? (Win)

Tim Chase python.list at tim.thechases.com
Sun Jan 31 14:41:55 EST 2010


Alf P. Steinbach wrote:
> that you cannot write e.g. "c:\windows\system32", but must
> write something like "c:\\windows\\system32" (try to print
> that string), or, since Windows handles forward slashes as
> well, you can write "c:/windows/system32" :-).

Forward slashes work for some relative paths for some commands 
but not for others like absolute non-drive-specified paths:

Microsoft Windows XP [Version 5.1.2600]
C:\>md abc
C:\>md abc\123
C:\>md abc\234
C:\>cd abc
C:\abc>tree /f /a
Folder PATH listing
Volume serial number is 940C-3F80
C:.
+---123
|   \---234
\---234

C:\abc>cd 123
C:\abc\123>cd ../234
C:\abc\234>type ../123/234/hello.txt
The syntax of the command is incorrect.
C:\abc\234>cd ../123
C:\abc\123>cd /abc/123
The system cannot find the path specified.
C:\abc>x:
X:\>type c:/abc/123/234/hello.txt
The syntax of the command is incorrect.

#####
The previous absolute-path fails in cmd.exe for a variety of apps 
because the "/" is treated as a parameter/switch to the various 
programs.  Fortunately, the Python path-handling sub-system is 
smart enough to do the right thing, even when Win32's internal 
handling is too dumb to behave:

C:\abc\123>echo hello > 234/hello.txt
C:\abc\123>cd ..
C:\abc>tree /f /a
Folder PATH listing
Volume serial number is 940C-3F80
C:.
+---123
|   \---234
|           hello.txt
|
\---234

C:\abc>python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> file('/abc/123/234/hello.txt').read()
'hello \n'

So as long as you stick within Python's insulation, forward 
slashes are a nice solution.  But if you have to interact with 
external programs, use the \\ notation or raw strings:

   pth = r"c:\windows\system32"

[mutters under breath about Win32 headaches]

-tkc






More information about the Python-list mailing list