At 05:33 PM 2/3/2011, Westley Martínez wrote:
On Thu, 2011-02-03 at 23:11 +0000, Steven D'Aprano wrote:
On Thu, 03 Feb 2011 07:58:55 -0800, Ethan Furman wrote:
> Steven D'Aprano wrote:
[snip]

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
Paths that mix /s and \s are NOT valid on Windows. In one of the setup.py scripts I wrote I had to write a function to collect the paths of data files for installation. On Windows it didn't work and it was driving me crazy. It wasn't until I realized os.path.join was joining the paths with \\ instead of / that I was able to fix it.

def find_package_data(path):
    """Recursively collect EVERY file in path to a list."""
    oldcwd = os.getcwd()
    os.chdir(path)
    filelist = []
    for path, dirs, filenames in os.walk('.'):
        for name in filenames:
            filename = ((os.path.join(path, name)).replace('\\', '/'))
            filelist.append(filename.replace('./', 'data/'))
    os.chdir(oldcwd)
    return filelist

Please check out os.path.normpath() as suggested.  Example:
    >>> import os
    >>> s = r"/hello\\there//yall\\foo.bar"
    >>> s
    '/hello\\\\there//yall\\\\foo.bar'
    >>> v = os.path.normpath(s)
    >>> v
    '\\hello\\there\\yall\\foo.bar'

The idea behind os.path is to cater to the host OS. Thus os.path.normpath() will convert to the host's acceptable delimiters. That is, you didn't need the .replace(), but rather to more fully use the existing library to good advantage with .normpath().

However, note that delimiters becomes an issue only when directly accessing the host OS, such as when preparing command line calls or accessing native APIs. Within the Python library/environment, both '/' and '\' are acceptable. External use is a different matter.

So, you need to be specific on how and where your paths are to be used. For instance os.chdir() will work fine with a mixture, but command line apps or native APIs will probably fail.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to