728x90
반응형
통상적으로 glob이나 os.listdir로 파일 리스트를 정리하고, 이를 sorting해주면 아래와 같이 정렬된다.
파일명을 문자열로 인식하기 때문에 아래처럼 정렬되는데, 이를 natsort라는 python package로 정렬해주면 우리가 원하는 파일 정렬이 가능하다.
3. natsort API — natsort 8.2.0 documentation
out – The sequence ordered by index, as a list or as an iterator (depending on the value of iter).
natsort.readthedocs.io
# 기존 방식
sorted(file_list)
"""
file_1.jpg
file_10.jpg
file_11.jpg
file_12.jpg
file_13.jpg
file_14.jpg
...
file_2.jpg
file_20.jpg
file_21.jpg
file_22.jpg
file_23.jpg
...
file_9.jpg
file_91.jpg
file_92.jpg
file_93.jpg
file_94.jpg
file_95.jpg
file_96.jpg
file_97.jpg
file_98.jpg
file_99.jpg
"""
예제 코드
# pip install natsort로 설치
import natsort
natsort.natsorted(file_list)
"""
file_1.jpg
file_2.jpg
file_3.jpg
file_4.jpg
file_5.jpg
file_6.jpg
...
file_99.jpg
"""
도움 주신 사이트: https://mentha2.tistory.com/171
[Python] 텍스트로 된 숫자(파일명) 정렬하기 natsort 라이브러리 활용
Python에서 natsort 라이브러리를 활용해 텍스트로 된 숫자 정렬하는 방법입니다. natsort 라이브러리의 natsorted() 메서드를 사용하면 텍스트를 쉽게 정렬할 수 있습니다. 상세 코드와 html 파일도 하단
mentha2.tistory.com
728x90
반응형