[Tutor] escaping slashes in filenames..
Daniel Yoo
dyoo@hkn.eecs.berkeley.edu
Thu, 10 May 2001 03:40:06 -0700 (PDT)
On Thu, 10 May 2001, Sharriff Aina wrote:
> aa =3D 'c:\ten\ten\ten\ten.jpg
> aa2 =3D string.replace(aa, '\t', '\\') # this results in
> 'c:\\en\\en\\en\\en.jpg'
> aa3 =3D string.replace(aa,'\', '\\\\') # 'c:\\\\en\\\\......
>=20
> My question is: how do I notify Python that the slashes are part of a
> filename and not an escaped character? using r'c:\test'; raw string is n=
ot
You can double up the backslashes. An escaped backslash is a backslash. =
=20
Er, what I mean is:
###
>>> backslash =3D '\\'
>>> backslash
'\\'
>>> print backslash
\
###
So one way to write out your path would be:
aa =3D 'c:\\ten\\ten\\ten\\ten.jpg
which would avoid the problem of accidently escaping the t's into tab
characters.
> filename and not an escaped character? using r'c:\test'; raw string is n=
ot
> an option because I=B4ve got to take care of a bunch of filenames in a li=
st
> or Tuple
I'm not quite sure I understand; can you show us what prevents the use of
raw strings? Perhaps there might be a way to get it to work.
For example, as long as there aren't any spaces in your filenames, you
could do something like:
###
long_list =3D r'''c:\test.txt,
c:\arm\and\a\leg.txt
c:\one\ring\to\rule\them\all.com'''.split()
###
which has the nice effect of using the split to break it into a 3-element
list. This is almost equivalent to Perl's "quoteword" function qw().
Hope this helps!