Pythonでファイルパス(ディレクトリ)の一部を抽出する 質問する

Pythonでファイルパス(ディレクトリ)の一部を抽出する 質問する

特定のパスの親ディレクトリの名前を抽出する必要があります。次のようになります。

C:\stuff\directory_i_need\subdir\file.jpg

抽出したいと思いますdirectory_i_need

ベストアンサー1

import os
## first file in current dir (with full path)
file = os.path.join(os.getcwd(), os.listdir(os.getcwd())[0])
file
os.path.dirname(file) ## directory of file
os.path.dirname(os.path.dirname(file)) ## directory of directory of file
...

これを必要に応じて何度でも続けることができます...

編集: os.pathからは、os.path.split または os.path.basename のいずれかを使用できます。

dir = os.path.dirname(os.path.dirname(file)) ## dir of dir of file
## once you're at the directory level you want, with the desired directory as the final path node:
dirname1 = os.path.basename(dir) 
dirname2 = os.path.split(dir)[1] ## if you look at the documentation, this is exactly what os.path.basename does.

おすすめ記事