0
votes

System: Python 2.6 on Windows 7 64 bit

Recently I did a lot of path formatting in Python. Since the string modifications are always dangerous I started to do it the proper way by using the 'os.path' module.

The first question is if this is the right way to to handle incoming paths? Or can I somehow optimize this?

sCleanPath = sRawPath.replace('\n', '')
sCleanPath = sCleanPath.replace('\\', '/')
sCleanPythonPath = os.path.normpath(sCleanPath)

For formatting the 'sCleanPythonPath' now I use only functions from the 'os.path' module. This works very nice and I didn't had any problems so far.

There is only one exception. I have to change paths so they point not longer on a network storage but on a local drive. Is started to use 'os.path.splitunc()' in conjunction with 'os.path.join()'.

aUncSplit = os.path.splitunc(sCleanPythonUncPath)
sLocalDrive = os.path.normpath('X:/mount')
sCleanPythonLocalPath = (os.path.join(sLocalDrive, aUncSplit[1]))

Unfortunately this doesn't work due to the nature of how absolute paths are handled using 'os.path.join()'. All the solutions I found in the web are using string replacements again which I want to avoid by using the 'os.path' module. Have I overseen anything? Is there another, maybe a better way to do this?

All comments on this are very welcome!

1
What are you getting with os.path.join and what do would you like to get? I dont see what you need to use regex for. - myusuf3
@myusuf3: Let's say sCleanPythonUncPath is //host/mount/folder/file.ext then I would like to get X:/mount/folder/file.ext. Unfortunately os.path.join() only returns /folder/file.ext, because it handles it like an absolute path. What regex calls do you mean? The calls of replace()? - Mr. Dice
Sometimes \ is valid as in C:\Program\ Files to be careful and always check. - sotapme
So would I do the replacement of the backslashes with a regular expression which excludes escape characters? - Mr. Dice

1 Answers

0
votes

You could optimize the first part slightly by removing the replace() call because on Windows normpath() converts forward slashes to backward slashes:

sCleanPath = sRawPath.replace('\n', '')
sCleanPythonPath = os.path.normpath(sCleanPath)

Here's something that would make the second part of your question work without doing a string replacement:

sSharedFolder = os.path.relpath(os.path.splitunc(sCleanPythonUncPath)[1], os.sep)
sLocalDrive = os.path.normpath('X:/mount')  # why not hardcode the result?
sCleanPythonLocalPath = os.path.join(sLocalDrive, sSharedFolder)