LoginSignup
0
1

More than 3 years have passed since last update.

指定した拡張子を持つファイルを調べて、ファイル名の配列を返すメソッド

Last updated at Posted at 2020-11-27

1. 定義したメソッド

Python
def get_ext_matching_file_names(ext_pattern_list, search_directory_path) :
      file_names_list = os.listdir(search_directory_path)
      # 上記のいずれかの拡張子を持つファイルのファイル名を格納する配列を用意
      available_filename_list = [] 
      # 上記のいずれかの拡張子を持つファイルのファイル名を配列に格納する
      for file_name in file_names_list:
           ext_check_result = []
           for ext in ext_pattern_list:
                 boolean = ext in file_name
                 ext_check_result.append(boolean)
           if True in ext_check_result:
                available_filename_list.append(file_name)
      return  available_filename_list

2. 使い方

カレントディレクトリに格納されているファイルを対象に、実行する場合は、以下のコードで実行します。

Python
import os.path

# カレントディレクトリの絶対パスを取得
current_directory_path = os.getcwd()
# abstract_path = os.path.abspath()

# 探したいファイルの拡張子
available_ext_list = ['pdf', 'docx', 'xlsx', 'pptx']

file_list = get_ext_matching_file_names(available_ext_list, current_directory_path)

print(file_list)
# 出力例
['sample.xlsx', 'siryou1.pptx', 'sample.docx']
0
1
2

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
1