可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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