2013-02-22 9 views
33

ファイルが存在するディレクトリを取得します。私はこのようにそれを行うことができPythonの絶対ファイルパスのディレクトリパスを取得します

fullpath = "/absolute/path/to/file" 
# something like: 
os.getdir(fullpath) # if this existed and behaved like I wanted, it would return "/absolute/path/to" 

:たとえばフルパスです

dir = '/'.join(fullpath.split('/')[:-1]) 

をしかし、上記の例では、特定のディレクトリの区切りに依存していると本当にきれいではありません。より良い方法がありますか?

+2

http://docs.python.org/2/library/os.path.html#os.path。 dirname –

答えて

53

あなたはこのを探しています:

>>> import os.path 
>>> fullpath = '/absolute/path/to/file' 
>>> os.path.dirname(fullpath) 
'/absolute/path/to' 

関連機能:

>>> os.path.basename(fullpath) 
'file' 
>>> os.path.split(fullpath) 
('/absolute/path/to','file') 
関連する問題