LoginSignup
0
0

pythonでディレクトリ内のサブディレクトリ名やパスを取得する

Last updated at Posted at 2024-06-02

概要

今回はディレクトリ内のサブディレクトリ名やパスを取得する方法について記載していきます。
勉強用に簡易的に記載していますので、ご了承ください。

実行環境

・windows:Windows11Pro 23H2
・Python 3.12.3

スクリプト

subfolder.py
import os
import itertools
import glob



folder_path = r"パス"

# 1)指定したディレクトリ内のファイルパスを全て表示する
def show_file_path():
    for current_dir, sub_dirs, files_list in os.walk(folder_path): 
        for file_name in files_list:
            print(os.path.join(current_dir,file_name))

# 2)指定したディレクトリ内のサブフォルダ名パスを全て表示する
def show_subfolder_path():
    for current_dir, sub_dirs, files_list in os.walk(folder_path): 
        for sub_dir_name in sub_dirs:
            print(os.path.join(current_dir,sub_dir_name))

# 3)指定したディレクトリ内のサブフォルダ名を全て取得する
def get_subfolder_name():
    subfolder_name = []
    for current_dir, sub_dirs, files_list in os.walk(folder_path):
        subfolder_name.append(sub_dirs)

    # 二次元配列を一次元配列にする
    subfolder_name =  list(itertools.chain.from_iterable(subfolder_name))

# 4)指定したディレクトリ内のディレクトリとサブディレクトリのパスを全て取得する
def folder_name():
    file_path_lists = glob.glob("{}/**".format(folder_path), recursive=True)
    folder_path_lists = []
    for file_path in file_path_lists:
        if (os.path.isdir(file_path)):
            folder_path_lists.append(file_path)

if __name__ == '__main__':
    show_file_path()
    show_subfolder_path()
    get_subfolder_name()
    folder_name()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0