Python Convert Back Slashes to forward slashes

匿名 (未验证) 提交于 2019-12-03 02:03:01

问题:

I am working in python and I need to convert this:

C:\folderA\folderB to C:/folderA/folderB

I have three approaches:

dir = s.replace('\\','/')  dir = os.path.normpath(s)   dir = os.path.normcase(s) 

In each scenario the output has been

C:folderAfolderB

I'm not sure what I am doing wrong, any suggestions?

回答1:

Your specific problem is the order and escaping of your replace arguments, should be

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

Then there's:

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

Which on a *nix platform is equivalent to:

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

But don't rely on that on Windows because it will prefer the platform-specific separator. Also:

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.



回答2:

Try

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


回答3:

How about :

import ntpath import posixpath . . . dir = posixpath.join(*ntpath.split(s)) . . 


回答4:

To define the path's variable you have to add r initially, then add the replace statement .replace('\\', '/') at the end.

for example:

In>>  path2 = r'C:\Users\User\Documents\Project\Em2Lph\'.replace('\\', '/') In>>  path2  Out>> 'C:/Users/User/Documents/Project/Em2Lph/' 

This solution requires no additional libraries



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!