jonathan topf
jonathan topf

Reputation: 8367

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

Upvotes: 8

Views: 17011

Answers (5)

Daniel Li
Daniel Li

Reputation: 15379

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")

If the input path is in Posix notation and you want automatically convert to Windows or Posix:

import os

path = "foo/bar/file.txt"
print os.path.join(*path.split("/"))

Upvotes: 0

Kevin Lee
Kevin Lee

Reputation: 1

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'

Upvotes: 0

phispi
phispi

Reputation: 859

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

Upvotes: 12

Mo'men Ahmed
Mo'men Ahmed

Reputation: 61

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.

Upvotes: 3

Burhan Khalid
Burhan Khalid

Reputation: 174624

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'

Upvotes: 7

Related Questions