开发者

Find directory of a file in Python

开发者 https://www.devze.com 2023-03-26 16:04 出处:网络
If I have the following file: file = \'/Users/d开发者_运维百科avid542/Desktop/work.txt\' I can use os.path.basename(file) to get the file name.

If I have the following file:

file = '/Users/d开发者_运维百科avid542/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") ?


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.


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消