Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find directory of a file in Python

Tags:

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") ?

like image 273
David542 Avatar asked Jan 26 '26 05:01

David542


1 Answers

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.

like image 93
Kai Avatar answered Jan 28 '26 20:01

Kai