[Tutor] How to replace the '\'s in a path with '/'s?

Steven D'Aprano steve at pearwood.info
Sun Jul 31 18:37:09 CEST 2011


Sergey wrote:
> Gotcha!
> http://pymon.googlecode.com/svn/tags/pymon-0.2/Internet/rsync.py
> 231-239 strings
> 
> ## code ##
> 
> def convertPath(path):
> 	# Convert windows, mac path to unix version.
> 	separator = os.path.normpath("/")
> 	if separator != "/":
> 		path = re.sub(re.escape(separator), "/", path)

The above code is buggy. It doesn't work as expected on a classic Mac. 
Hint: import macpath; print macpath.normpath('/')

Besides, there is no need to use the 20 lb sledgehammer of regular 
expressions to crack the tiny little peanut of replacing a simple 
character with another simple character.

The above function is much more sensibly written as:

def convertPath(path):
     separator = os.path.sep
     if sep != '/':
         path = path.replace(os.path.sep, '/')
     return path

Or even more simply:

     return path.replace(os.path.sep, '/')

(although that may do a small amount of unnecessary work on Unix systems).




-- 
Steven



More information about the Tutor mailing list