「Python」listdir関数でフォルダの中のファイルを取得する

環境

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
PyCharm 2021.3
Python 3.9.7
PyCharm 2021.3 Python 3.9.7
PyCharm 2021.3
Python 3.9.7

書式
os.listdir(フォルダのパス)
listdir関数を使ってフォルダの中のファイルを取得します。
「\」をエスケープする必要があるため、「\」であれば「\\」と記述します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
print("フォルダの中のファイルを取得する結果")
print(os.listdir('C:\\study\\skill\\python'))
import os print("フォルダの中のファイルを取得する結果") print(os.listdir('C:\\study\\skill\\python'))
import os

print("フォルダの中のファイルを取得する結果")
print(os.listdir('C:\\study\\skill\\python'))

実行結果

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
フォルダの中のファイルを取得する結果
['test.py', 'test001.xlsx', 'test002.xlsx']
フォルダの中のファイルを取得する結果 ['test.py', 'test001.xlsx', 'test002.xlsx']
フォルダの中のファイルを取得する結果
['test.py', 'test001.xlsx', 'test002.xlsx']

 

Python

Posted by arkgame