Python
sorted와 natsorted 차이 (sorted의 파일명 정렬 시 문제점)
교 향
2024. 3. 29. 11:45
python natsort로 파일을 "이름 순으로" 정렬해보자
python으로 데이터를 다룰 때 파일 경로의 리스트를 읽어오는 불러오는 경우가 많습니다. 저는 파일 이름을 순서대로 정렬해 가져와야 했습니다. 이 단순한 작업이 겉으로는 쉬워 보이지만, 처음
lovedh.tistory.com
평소 우리가 생각하는 숫자 정렬은 0,1,2,3,..9,10,11 을 생각하지만 막상 sorted로 파일을 정렬하면 아래와 같이 이상하다.
※ 단순 sorted()로 파일명 정렬 시 (ex. 0.jpg, 1.jpg, ...)
0, 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, ....
import os
print(sorted( os.listdir('data') ))
!!! 하여 아래와 같이 마음 편히 natsorted()를 사용함이 편하겠다.
※ natsorted()로 파일명 정렬 시 (ex. 0.jpg, 1.jpg, ...)
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ...
→ 코드 예시
pip install natsort
import os
import natsort
print(natsort.natsorted(os.listdir('data')))