PYTHON dirname

is this article helpful?
Python replacement for PHP's dirname [ edit | history ]
import os
os.path.dirname(path.rstrip(os.pathsep)) or '.'

If you'd like PHP's dirname function to behave more like Python's, you can do the following

$dir = dirname($path.'.');

PHP dirname

PHP original manual for dirname [ show | ]


(PHP 4, PHP 5)

dirnameReturns directory name component of path


string dirname ( string $path )

Given a string containing a path to a file, this function will return the name of the directory.



A path.

On Windows, both slash (/) and backslash (\) are used as directory separator character. In other environments, it is the forward slash (/).

Return Values

Returns the name of the directory. If there are no slashes in path , a dot ('.') is returned, indicating the current directory. Otherwise, the returned string is path with any trailing /component removed.


Version Description
5.0.0 dirname() is now binary safe
4.0.3 dirname() was fixed to be POSIX-compliant.


Example #1 dirname() example

$file dirname($path); // $file is set to "/etc"


Note: Since PHP 4.3.0, you will often get a slash or a dot back from dirname() in situations where the older functionality would have given you the empty string.

Check the following change example:


//before PHP 4.3.0
dirname('c:/'); // returned '.'

//after PHP 4.3.0
dirname('c:/x'); // returns 'c:\'
dirname('c:/Temp/x'); // returns 'c:/Temp'
dirname('/x'); // returns '\'


See Also

  • basename() - Returns filename component of path
  • pathinfo() - Returns information about a file path
  • realpath() - Returns canonicalized absolute pathname