How can I extract the folder path from file path in Python?

Question:

I would like to get just the folder path from the full path to a file.

For example T:DataDBDesignDBDesign_93_v141b.mdb and I would like to get just T:DataDBDesign (excluding the DBDesign_93_v141b.mdb).

I have tried something like this:

existGDBPath = r'T:DataDBDesignDBDesign_93_v141b.mdb'
wkspFldr = str(existGDBPath.split('\')[0:-1])
print wkspFldr 

but it gave me a result like this:

['T:', 'Data', 'DBDesign']

which is not the result that I require (being T:DataDBDesign).

Any ideas on how I can get the path to my file?

Asked By: Genspec

||

Answers:

The built-in submodule os.path has a function for that very task.

import os
os.path.dirname('T:DataDBDesignDBDesign_93_v141b.mdb')
Answered By: Dan Allan

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(r'T:DataDBDesignDBDesign_93_v141b.mdb')
>>> wkspFldr = existGDBPath.parent
>>> print wkspFldr
Path('T:DataDBDesign')

WITH OS MODULE

Use the os.path module:

>>> import os
>>> existGDBPath = r'T: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 it’s already been implemented in os.path. If not, you’ll still probably need to use this module as the building block.

Answered By: SethMMorton

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 it’ll 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')
Answered By: Sukrit Kalra

Here is the code:

import os
existGDBPath = r'T:DataDBDesignDBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:DataDBDesign
Answered By: Victor Lellis

Here is my little utility helper for splitting paths int file, path tokens:

import os    
# usage: file, path = splitPath(s)
def splitPath(s):
    f = os.path.basename(s)
    p = s[:-(len(f))-1]
    return f, p
Answered By: Timothy C. Quinn

Anyone trying to do this in the ESRI GIS Table field calculator interface can do this with the Python parser:

PathToContainingFolder =

"\".join(!FullFilePathWithFileName!.split("\")[0:-1])

so that

UsersmeDesktopNew folderfile.txt

becomes

UsersmeDesktopNew folder

Answered By: Zipper1365

I use this to change the current working directory to a folder;

from os import chdir
from os.path import realpath
from os.path import dirname

chdir(realpath(dirname(argv[0])))
  • chdir changes the working directory. I doubt you’ll need this.
  • realpath follows symlinks.
  • dirname returns just the path
  • argv is the command line used to execute the program
Answered By: bauderr
Categories: questions Tags: , , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.