some path issues on windows

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Mar 29 04:21:34 CET 2008


On Fri, 28 Mar 2008 22:31:07 -0400, Brad wrote:

> When reading a file into a list that contains windows file paths like
> this:
> 
> c:\documents and settings\brad\desktop\added_software\asus\a.txt
> 
> I get a list that contains paths that look like this:
> 
> c:\\documents and settings\\brad\\desktop\\added_software\\asus\\a.txt


What makes you think that there are doubled backslashes in the string? 
Look at this:


>>> path = r'C:\docs\file.txt'  # Single backslashes
>>> path
'C:\\docs\\file.txt'
>>> print path
C:\docs\file.txt
>>> len(path)
16

Despite how it looks, the backslashes are all singles, not doubles:

>>> path[2]
'\\'
>>> len(path[2])
1

When you display strings, by default special characters are escaped, 
including backslashes. (Otherwise, how could you tell whether the \f in 
the path meant backslash followed by f or a formfeed?)

Python interprets backslashes as special when reading string literals, 
NOT when reading them from a file:

>>> open('backslash.txt', 'w').write('docs\\files')
>>> s = open('backslash.txt', 'r').read()
>>> s
'docs\\files'
>>> print s
docs\files
>>> len(s)
10



-- 
Steven



More information about the Python-list mailing list