5

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
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
jonathan topf
  • 7,897
  • 17
  • 55
  • 85

5 Answers5

6

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'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
6

The pathlib module (introduced in Python 3.4) has support for this:

from pathlib import PureWindowsPath, PurePosixPath

# Windows -> Posix
win = r'foo\bar\file.txt'
posix = str(PurePosixPath(PureWindowsPath(win)))
print(posix)  # foo/bar/file.txt

# Posix -> Windows
posix = 'foo/bar/file.txt'
win = str(PureWindowsPath(PurePosixPath(posix)))
print(win)  # foo\bar\file.txt
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
phispi
  • 604
  • 7
  • 15
3

Converting to Unix:

import os
import posixpath
p = "G:\Engineering\Software_Development\python\Tool"
p.replace(os.sep, posixpath.sep)

This will replace the used-os separator to Unix separator.

Converting to Windows:

import os
import ntpath
p = "G:\Engineering\Software_Development\python\Tool"
p.replace(os.sep, ntpath.sep)

This will replace the used-os separator to Windows separator.

Mo'men Ahmed
  • 61
  • 1
  • 4
0

os.path.join will intelligently join strings to form filepaths, depending on your OS-type (POSIX, Windows, Mac OS, etc.)

Reference: http://docs.python.org/library/os.path.html#os.path.join

For your example:

import os

print os.path.join("foo", "bar", "file.txt")
Daniel Li
  • 14,976
  • 6
  • 43
  • 60
0

since path is actually a string, you can simply use following code:

p = '/foo/bar/zoo/file.ext'
p = p.replace('/', '\\')

output:

'\\foo\\bar\\zoo\\file.ext'
Kevin Lee
  • 1
  • 1