코린이/실무를 위한 코딩 기록
[python] 폴더/하위 폴더의 파일 목록 출력
anweh
2021. 6. 4. 14:54
1. 특정 형태의 파일 위치 출력
import os
import pandas as pd
import csv
PATH = r'C:/Users/82107/Desktop/COMPAS_세종시/'
file_ls = []
max_depth = 0
for path, dir, files in os.walk(PATH):
for file in files:
current = os.path.join(path, file).replace('\\', '/')
file_ls.append(current)
if len(current.split('/')) > max_depth:
max_depth = len(current.split('/'))
- PATH에 mother root을 입력
- 해당 코드는 pdf 파일의 위치만 추출하는 것인데, 만약에 csv 파일의 위치를 추출하고 싶다면 if 문을 수정하면 된다
2. 폴더와 하위폴더 내 모든 파일 목록을 확인하고 싶다면? (데이터 입수)
import os
import pandas as pd
import csv
PATH = r'C:/Users/82107/Desktop/COMPAS_세종시/'
file_ls = []
max_depth = 0
for path, dir, files in os.walk(PATH):
for file in files:
current = os.path.join(path, file).replace('\\', '/')
file_ls.append(current)
if len(current.split('/')) > max_depth:
max_depth = len(current.split('/'))
csv_path = 'C:/Users/82107/Desktop/'
os.chdir(csv_path)
depth = list(range(0, max_depth, 1))
with open('folder_data.csv', 'w', newline='', encoding='cp949') as f:
w = csv.writer(f)
w.writerow(' '.join(str(e) for e in depth).split())
for path, dir, files in os.walk(PATH):
for file in files:
current = os.path.join(path, file).replace('\\', '/')
row = os.path.relpath(current, PATH).split(os.sep)
w.writerow(row)
df = pd.read_csv('folder_data.csv', error_bad_lines=False, index_col=None,
header=0, engine='python', encoding='cp949')
- 폴더의 깊이만큼 열을 만들고 (depth)
- 파일 경로를 '/' 단위로 잘라서 행 값으로 입력해준다
- 이때 특정 형태의 파일만 조사하고 싶다면 1번과 같이 if 문을 추가해주면 된다