Reputation: 25094
I am trying to convert a path into its components in a pythonic way.
Example:
path = /drive/dir/anotherdir/finaldir/
Approach:
splitted = path.split(os.path.sep)
>>> ['', 'drive', 'dir', 'anotherdir', 'finaldir', '']
Wanted Output:
>>> ['drive', 'dir', 'anotherdir', 'finaldir']
Is there a cleaner way so that there are no empty string entries? It's easy to get around with slicing but it just adds unwanted noise. I looked into the os.path module and the only splitters are:
os.path.split(path)
os.path.splitdrive(path)
os.path.splitext(path)
os.path.splitunc(path)
P.S.: i am not looking for a solution i just want to make sure if there is a solution i didn't take intto account.
Upvotes: 3
Views: 1255
Reputation: 46
What Mark Ransom is saying is that your Wanted Output is invalid, given the possible values path
could take. When talking about paths, the OS has some conventions regarding how to resolve a path string to a file or directory.
Consider the following code:
def toComponents(path):
return path.split('/')
def fromComponents(components):
return '/'.join(components)
# specialToComponents takes a path and returns
# the components relative to the / folder or
# if the path is relative, it returns the components
# Use at your own risk.
def specialToComponents(path):
return path.strip('/').split('/')
Suppose you have two paths:
path = /drive/dir/anotherdir/finaldir/
This is an absolute path, which tells the reader and the OS that the file is located inside the /
folder, inside the path
folder and so on, until finaldir/
path = drive/dir/anotherdir/finaldir/
This is a relative path. It conventionally means relative to the program's current directory. It says go to the current directory, then go to drive
then dir
and so on, until finaldir/
.What you're trying to do is read absolute paths as relative ones and relative ones as relative ones, which is great, if only it doesn't cause headaches for you when someone tries to run your code against an absolute path.
Upvotes: 1