179

What is the difference between os.path.basename() and os.path.dirname()?

I already searched for answers and read some links, but didn't understand. Can anyone give a simple explanation?

SherylHohman
  • 16,580
  • 17
  • 88
  • 94
user1429210
  • 1,959
  • 2
  • 12
  • 8

2 Answers2

343

Both functions use the os.path.split(path) function to split the pathname path into a pair; (head, tail).

The os.path.dirname(path) function returns the head of the path.

E.g.: The dirname of '/foo/bar/item' is '/foo/bar'.

The os.path.basename(path) function returns the tail of the path.

E.g.: The basename of '/foo/bar/item' returns 'item'

From: http://docs.python.org/3/library/os.path.html#os.path.basename

user5994461
  • 5,301
  • 1
  • 36
  • 57
Breno Teixeira
  • 3,860
  • 2
  • 19
  • 17
  • 28
    Remember that if you replace `item` with `item/`, which is a directory, then `os.path.split('foo/bar/item/')` returns `('foo/bar/item', '')`. – jkdev May 04 '17 at 17:24
  • 1
    what will happen if the path is a file, say, "foo.bar"? – ZhaoGang Sep 26 '18 at 13:11
  • 6
    @jkdev Yes, if you want to get the last directory name in a path, you should use: `os.path.basename(os.path.dirname(path))` – alwaysday1 Nov 26 '18 at 07:27
  • 1
    @ZhaoGang If the entire path is just a file name, then os.path.basename(file_name) returns the file name: here, `'foo.bar'`, and os.path.dirname(file_name) returns an empty string: `''`. – jkdev Nov 26 '18 at 20:47
10

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Umar Dastgir
  • 688
  • 9
  • 25