Double backslash in filepaths ?

John J. Lee jjl at pobox.com
Sat Apr 14 06:33:38 EDT 2007


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



More information about the Python-list mailing list