본문 바로가기
프로그래밍/Python

[Python] '문자+숫자'로 구성된 파일명 정렬하기

by rahites 2023. 1. 14.

# frame0.jpg, frame1.jpg ... frame535.jpg 형태의 파일명을 가지는 디렉토리에서 *.jpg 형태로 모든 파일명을 glob 해오자 정렬이 되지 않고 순서가 뒤죽박죽이 되는 문제 발생

# 단순히 sorted를 사용할 경우 -> 0, 1, 10, 11 이런식으로 정렬이 됨!

 

해결

# pip install natsort
from natsort import natsorted

natsort 패키지를 이용하면 문자와 숫자가 합쳐진 파일명에서도 숫자 순서대로 정렬할 수 있다.

ex. natsorted(glob('*.jpg')) -> frame0.jpg, frame1.jpg ......

 

 

(너무 신기해서 까먹지 않게 바로 기록!!)

https://stackoverflow.com/questions/33159106/sort-filenames-in-directory-in-ascending-order

 

Sort filenames in directory in ascending order

I have a directory with jpgs and other files in it, the jpgs all have filenames with numbers in them. Some may have additional strings in the filename. For example. 01.jpg Or it could be Pictur...

stackoverflow.com

 

댓글