Python将反斜杠转换为正斜杠

2024-09-30 07:21:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中工作,需要转换以下内容:

C:\folderA\folderB到C:/folderA/folderB

我有三种方法:

dir = s.replace('\\','/')

dir = os.path.normpath(s) 

dir = os.path.normcase(s)

在每个场景中,输出都是

C:文件夹文件夹

我不知道我做错了什么,有什么建议吗?


Tags: path方法文件夹osdir场景建议replace
3条回答

您的具体问题是replace参数的顺序和转义,应该是

s.replace('\\', '/')

然后是:

posixpath.join(*s.split('\\'))

在*nix平台上相当于:

os.path.join(*s.split('\\'))

但不要依赖Windows,因为它更喜欢特定于平台的分隔符。另外:

Note that on Windows, since there is a current directory for each drive, os.path.join("c:", "foo") represents a path relative to the current directory on drive C: (c:foo), not c:\foo.

试试看

path = '/'.join(path.split('\\'))

我最近发现这一点,并认为值得分享:

import os

path = "C:\\temp\myFolder\example\\"

newPath = path.replace(os.sep, '/')

print newPath


Output:<< C:/temp/myFolder/example/  >>

相关问题 更多 >

    热门问题