Python 기초
파이썬, 특정 디렉터리를 모두 탐색 예제
수알치
2023. 4. 8. 17:08
# 현재 드라이브에서 지정한 디렉터리를 모두 탐색 예제
import os
# 현재 드라이브의 루트 경로를 가져옴
drive = os.getenv("SystemDrive")
# 현재 드라이브에 temp 디렉터리 결합
root_path = drive + "\\temp"
# 파일 경로를 저장할 리스트를 생성
file_list = []
# 지정한 디렉티리의 모든 파일을 검색
for dirpath, dirnames, filenames in os.walk(root_path):
for filename in filenames:
file_path = os.path.join(dirpath, filename)
file_list.append(file_path.split(os.sep))
# 파일 경로 리스트를 출력
for file_path in file_list:
print(file_path)
[실행 결과]
['C:', 'temp', 'kisoo.pem']
['C:', 'temp', 'log.txt']
['C:', 'temp', 'AUtempR', 'amoncdw567.sys']
['C:', 'temp', 'data', 'my1.json']
['C:', 'temp', 'data', 'my2.json']
['C:', 'temp', 'textfiles', 'test1.txt']
['C:', 'temp', 'textfiles', 'test2.txt']
반응형