[Tutor] escaping slashes in filenames..
Glen Wheeler
wheelege@tsn.cc
Thu, 10 May 2001 22:52:04 +1000
(just cc-ing this to the tutor list)
>
>Hi Glen!
>
Hi :)
>Message text written by "Glen Wheeler"
>>which is tedious
>and evil</assumption>.<
>
>on the dot, actually a search and replace works, but it fails when it
>encounters substrings with "escaped like characters" example:
>
>C:\good\image.jpg # this works
>
>c:\bad\image.jpg # this does´nt because Python thinks beforehand that a
>'\b' charater is in the string. this follows for other escaped charaters
>too.
>
>Using raw strings is not an option because the list of paths are generated
>dynamically. I would have loved to turn them all into raw strings and write
>them back in the list but all my functions failed.
Alright, then perhaps the function in question needs a look at. For
example, say your generating the path using a script like this...
------------
## generate a random path made up of a C: at the start, and a variable
number of directories made up of upper and lowercase letters
import string, random
def makepath():
path = r'C:' ## not sure if this is important, but I did it
anyway
somechars = list(string.letters)
slashes = range(int(random.random()*9)) ## perhaps this should be a
bigger number
for x in slashes:
for y in range(int(random.random()*27)): ## same here
l = random.choice(somechars)
path = path + l
if x != slashes[-1]:
path = path + '\\' ## this is crucial
else:
return path
apath = makepath()
print apath
------------(could contain errors... I'm tired, didn't check it... :)
Now that I've written that.... it would be better to use
random.choice([1,2,3,4,5,6,7]) for the directory names...bah, it's not meant
to be useful, just illustrate how you would pre-escape a generated path.
If you are using a built-in function to get the path, it should already be
a string with escaped backslashes. If not, I hope we can help you modify
your existing function to return nice useable paths :)
Glen.