How can I extract the folder path from file path in Python?
How can I extract the folder path from file path in Python?
You were almost there with your use of the split
function. You just needed to join the strings, like follows.
>>> import os
>>> \.join(existGDBPath.split(\)[0:-1])
T:\Data\DBDesign
Although, I would recommend using the os.path.dirname
function to do this, you just need to pass the string, and itll do the work for you. Since, you seem to be on windows, consider using the abspath
function too. An example:
>>> import os
>>> os.path.dirname(os.path.abspath(existGDBPath))
T:\Data\DBDesign
If you want both the file name and the directory path after being split, you can use the os.path.split
function which returns a tuple, as follows.
>>> import os
>>> os.path.split(os.path.abspath(existGDBPath))
(T:\Data\DBDesign, DBDesign_93_v141b.mdb)
WITH PATHLIB MODULE (UPDATED ANSWER)
One should consider using pathlib for new development. It is in the stdlib for Python3.4, but available on PyPI for earlier versions. This library provides a more object-orented method to manipulate paths <opinion>
and is much easier read and program with </opinion>
.
>>> import pathlib
>>> existGDBPath = pathlib.Path(rT:DataDBDesignDBDesign_93_v141b.mdb)
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path(T:DataDBDesign)
WITH OS MODULE
Use the os.path module:
>>> import os
>>> existGDBPath = rT:DataDBDesignDBDesign_93_v141b.mdb
>>> wkspFldr = os.path.dirname(existGDBPath)
>>> print wkspFldr
T:DataDBDesign
You can go ahead and assume that if you need to do some sort of filename manipulation its already been implemented in os.path
. If not, youll still probably need to use this module as the building block.
How can I extract the folder path from file path in Python?
The built-in submodule os.path has a function for that very task.
import os
os.path.dirname(T:DataDBDesignDBDesign_93_v141b.mdb)