파일이름 변경하기

|

Python 3.3.3 버전 기준.


최하위 디렉토리명을 기준으로 파일명 일괄로 변경하기


#-*- coding: utf-8 -*-
#renmamer.py

import os
import sys

def usage():
	print("""
Usage(make by Teddy)
=====
python %s %%dirPath%%
=====
""" % (sys.argv[0]))

# 재귀적으로 하위 디렉토리 검색
def search(dirName, count=1):
	flist = os.listdir(dirName)
	for f in flist:
		next = os.path.join(dirName, f)
		if os.path.isdir(next):
			search(next)
		else:
			doFileWork(next, count)
			count = count + 1

# 파일 이름 변경  		
def doFileWork(fileName, count):
	ext = os.path.splitext(fileName)[-1]                         # 확장자
	newFileName = os.path.split(os.path.split(fileName)[0])[-1]  # 새파일이름
	dirName = os.path.dirname(fileName)                          # 디렉토리명
	dest = os.path.join(dirName, newFileName + "_%3s%s" % (str(count).zfill(3), ext))
	os.rename(fileName, dest)

# Main()
if len(sys.argv) == 2:
	print("***Start***")
	search(sys.argv[1])
	print("***End***")
else:
	usage()



renamer.py


And