如何将路径字符串的格式更改为不同的操作系统? [英] How to change the format of a path string to a different OS?

查看:36
本文介绍了如何将路径字符串的格式更改为不同的操作系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将文件路径从 MAC 更改为 Windows,我正准备使用 \<对任何 / 执行简单的 .replace()/code> 但我突然想到可能有更好的方法.例如,我需要更改:

foo/bar/file.txt

到:

foo\bar\file.txt

解决方案

你可以使用这个:

<预><代码>>>>s = '/foo/bar/zoo/file.ext'>>>导入路径>>>导入操作系统>>>s.replace(os.sep,ntpath.sep)'\\foo\\bar\\zoo\\file.ext'

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'

这篇关于如何将路径字符串的格式更改为不同的操作系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆