David542
David542

Reputation: 110093

Find directory of a file in Python

If I have the following file:

file = '/Users/david542/Desktop/work.txt'

I can use os.path.basename(file) to get the file name.

What command would I use to get the directory of the file (i.e., to get "/Users/david542/Desktop") ?

Upvotes: 2

Views: 338

Answers (4)

Kracekumar
Kracekumar

Reputation: 20419

os.path.dirname(file) will yield directory name.
import os
print(os.path.dirname("c:/windows/try.txt"))

Upvotes: 1

vstm
vstm

Reputation: 12537

I think you're searching for os.path.dirname. Otherwise you could use os.path.split which returns the path and the filename in a tuple.

Upvotes: 0

Kai
Kai

Reputation: 5320

os.path.dirname(file) returns the directory of the passed file name. Alternatively, you can use os.path.split(file) which will give you a tuple containing the directory name and the file name in one call.

Upvotes: 4

Senthil Kumaran
Senthil Kumaran

Reputation: 56823

>>> os.path.dirname(os.path.realpath('/Users/david542/Desktop/work.txt'))

Upvotes: 4

Related Questions