파이썬

파이썬으로 파일 이름 일괄 수정하기

Gamcho 2017. 11. 25. 16:04


import os


#os는 파이썬이 내 컴퓨터 파일에 접근할 수 있게 해주는 모듈

a=os.chdir('C:\\users\admin\Desktop\example')

for f in os.listdir():

#print(os.path.splitext(f)) -> print 함수로 출력하면서 오류 유무 확인

f_name, f_ext = os.path.splitext(f)

f_title, f_tag = f_name.split("-")


# split("-")) -> 파일명을 '빈칸' 기준으로 나눠줌

f_title=f_title.strip()
f_tag=f_tag.strip()[1:].zfill(2)

#strip() 빈칸 제거
#zfill() 0을 추가, 파일 번호순 정리시 유용

#print('{}-{}{}'.format(f_tag, f_title, f_ext))

new_name = '{}-{}{}'.format(f_tag, f_title, f_ext)

os.rename(f, new_name)