"2025/05"에 해당되는 글 - 1건
Post
import os
import re
file_path = '.\\pic'
file_names = os.listdir(file_path)
file_new_name = "이름"
i = 1
for name in file_names:
src = os.path.join(file_path, name)
dst = file_new_name + str(i) + '.jpg'
dst = os.path.join(file_path, dst)
os.rename(src, dst)
i += 1
위는 수정전 코드.
그냥 파일에 있는대로 FOR문 돌리니까 뭔가 생성된 순서대로
이름을 바꾸는 것 같아서 아래처럼
이름순 정렬 후에 이름바꾸기로 수정함
수정후
import os
import re
file_path = '.\\pic'
file_names = sorted(os.listdir(file_path))
file_new_name = "이름"
i = 1
for name in file_names:
src = os.path.join(file_path, name)
dst = file_new_name + str(i) + '.jpg'
dst = os.path.join(file_path, dst)
os.rename(src, dst)
i += 1
코드 안되면 수정하자!D
그리고 안되었다. SORT 가 글자로 인식해서 글자 순서대로 1, 10 이렇게 소트했음 ㅠㅠ
import os
import re
file_path = './pic'
file_names = os.listdir(file_path)
# 숫자만 추출해서 정렬
def extract_number(filename):
numbers = re.findall(r'\d+', filename)
return int(numbers[0]) if numbers else 0
file_names = sorted(file_names, key=extract_number)
file_new_name = "테스트"
i = 1
for name in file_names:
src = os.path.join(file_path, name)
dst = file_new_name + str(i) + '.jpg'
dst = os.path.join(file_path, dst)
os.rename(src, dst)
i += 1
이렇게 완료!
'이전게시판 > Python' 카테고리의 다른 글
파이썬 한글 글자수 체크 및 특정 단어 갯수 찾기 (0) | 2025.03.30 |
---|---|
python 폴더 내 파일 이름 변경 rename (0) | 2025.03.30 |
inconsistent use of tabs and spaces in indentation in Python (0) | 2024.04.18 |
ModuleNotFoundError: No module named 'pandas' 아나콘다가 깔려 있을 때 해결법 (0) | 2024.01.27 |
Python 크롤링 리스트 출력 (1) | 2023.04.10 |