简体   繁体   中英

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

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'

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM