pythonpathoperating-system

How to change the format of a path string to a different OS?


I need to change a file path from MAC to Windows and I was about to just do a simple .replace() of any / with \ but it occurred to me that there may be a better way. So for example I need to change:

foo/bar/file.txt

to:

foo\bar\file.txt

Solution

  • You can use this:

    >>> s = '/foo/bar/zoo/file.ext'
    >>> import ntpath
    >>> import os
    >>> s.replace(os.sep,ntpath.sep)
    '\\foo\\bar\\zoo\\file.ext'