Double backslash in filepaths ?

Stef Mientki S.Mientki-nospam at mailbox.kun.nl
Sat Apr 14 13:02:21 CEST 2007


John J. Lee wrote:
> Stef Mientki <S.Mientki-nospam at mailbox.kun.nl> writes:
> 
>> It looks like sometimes a single backslash is replaced by a double backslash,
>> but sometimes it's not ???
>> See the error message below,
>> the first backslash is somewhere (not explicitly in my code) replaced,
>> but the second is not ???
>> Is it in general better to use double backslash in filepaths ?
> [...]
>> IOError: [Errno 2] No such file or directory: 'D:\\data_to_test\test_global.pd'
> 
> '\t' is the tab character.  '\d' is not a valid escape sequence, so
> the backslash there survives intact.  repr() normalises the string on
> output, so the (single!) backslash in '\d' is displayed, as always in
> the repr of strings, as '\\'.
> 
> You should either use this:
> 
> 'D:\\data_to_test\\test_global.pd'
> 
> 
> Or this:
> 
> r'D:\data_to_test\test_global.pd'
> 
> See also:
> 
> http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings-end-with-a-backslash
> 
> 
> Or even this, which will work unless you're using crufty software that
> doesn't like slash path separators (cmd.exe being one of those pieces
> of software):
> 
> 'D:/data_to_test/test_global.pd'
> 
> 
> John

thanks John and Michael,
this is a very helpful explanation.

cheers,
Stef



More information about the Python-list mailing list