[Python].endswith関数で指定拡張子のファイルを取得する

環境
PyCharm 2021.3
Python 3.9.7

構文
os.listdir(ファイルパスの変数名)
listdir関数で指定ファイルパスのファイルをすべて取得します。
ファイルの末尾が拡張子「.txt」で終わっているファイルのみを「endswith」を使って取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
#ファイルのディレクトリ変数の宣言
fPath = 'C:\study\skill\python'
#指定ディレクトリの全てのファイル
for file in os.listdir(fPath):
# 拡張子「.xlsx」で終わるファイルを抽出
if file.endswith('.xlsx'):
print(fPath + '\\' + file)
import os #ファイルのディレクトリ変数の宣言 fPath = 'C:\study\skill\python' #指定ディレクトリの全てのファイル for file in os.listdir(fPath): # 拡張子「.xlsx」で終わるファイルを抽出 if file.endswith('.xlsx'): print(fPath + '\\' + file)
import os

#ファイルのディレクトリ変数の宣言
fPath = 'C:\study\skill\python'
#指定ディレクトリの全てのファイル
for file in os.listdir(fPath):
    # 拡張子「.xlsx」で終わるファイルを抽出
    if file.endswith('.xlsx'):
        print(fPath + '\\' + file)

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
C:\study\skill\python\test001.xlsx
C:\study\skill\python\test002.xlsx
C:\study\skill\python\test001.xlsx C:\study\skill\python\test002.xlsx
C:\study\skill\python\test001.xlsx
C:\study\skill\python\test002.xlsx

 

Python

Posted by arkgame