os.path.join doubt
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Thu Feb 3 18:11:08 EST 2011
On Thu, 03 Feb 2011 07:58:55 -0800, Ethan Furman wrote:
> Steven D'Aprano wrote:
>> BTW, Windows accepts / as well as \ as a path separator. You will have
>> far fewer headaches if you use that.
>
> Just because Windows accepts / doesn't make it a good idea...
No. Windows accepting slashes as the alternate path separator *enables*
you to use slash. What makes it a good idea is that you don't have to
worry about forgetting to escape backslashes:
>>> print("C:\temp\file.txt")
C: emp
ile.txt
Nor do you have to care about the fact that raw strings are designed for
regular expressions, not Windows path names, and you can't have a raw
string ending in a single backslash:
>>> location = r'C:\temp\' # Path ending in a backslash.
File "<stdin>", line 1
location = r'C:\temp\'
^
SyntaxError: EOL while scanning string literal
The fact is that Windows' use of backslash as the path separator
conflicts with Python's use of backslashes. Since our code is written in
Python, trying to uses backslashes causes problems. One work-around is to
take advantage of the fact that Windows has an alternate separator
character, and use that. If you'd rather use raw strings, and special-
case backslashes at the end of paths, go right ahead.
> --> from glob import glob
> --> print '\n'.join(glob('c:/temp/*')) c:/temp\0C2O0007.TMP
> c:/temp\27421
> c:/temp\3K540007.TMP
[...]
Yes. Is there a problem? All those paths should be usable from Windows.
If you find it ugly to see paths with a mix of backslashes and forward
slashes, call os.path.normpath, or just do a simple string replace:
path = path.replace('/', '\\')
before displaying them to the user. Likewise if you have to pass the
paths to some application that doesn't understand slashes.
--
Steven
More information about the Python-list
mailing list