[Python] 폴더내 파일명 일괄 변경

폴더내 파일명 일괄 변경


개발내용

플래시 컨텐츠 테스트를 위해 폴더내 파일명을 특정 패턴에 맞게 일괄로 변경해야 되는 이슈가 있어 개발.

개발환경

  • Language: Python 2.7.10
  • OS: Windows 7 64bit

소스코드
#-*- coding: utf-8 -*-
# ===============================================================
# Author: coozplz@gmail.com
# File: flash_korean_file_rename.py
# Date: 2015. 07. 14
# Desc: 플래시 샘플 컨텐츠들의 이름을 변경하기 위한 프로그램.
# ===============================================================

import os

def rename_flash_content(path, key, startIndex):
	'''
	플래시 샘플 컨테츠의 이름을 변경한다.
	:param path 루트 디렉토리 경로
	:param key 컨텐츠 구분값(명사: N, 형용사: A, 동사: V, 인사말:G)
	:param startIndex 컨텐츠 시작 번호
	'''
	print 'path=%s' % path
	minValue = i = startIndex;
	j = 1

	for item in os.listdir(root):
		# 파일명과 확장자를 분리한다.
		# item: 493-A023-c.swf
		# filename: 493-A023-c
		# file_extension: .swf
		filename, file_extension = os.path.splitext(item)

		if (file_extension != '.swf'):
			print 'invalid file name %s' % item
			continue;

		# item의 절대 경로를 구한다.
		fullpath = os.path.join(root, item)

		mod = j % 4
		suffix = 'a'
		if mod == 1:
		suffix = 'b'
		elif mod == 2:
		suffix = 'c'
		elif mod == 3:
		suffix = 'd'
		else:
		suffix = 'a'

		# 변경할 이름의 포맷을 정의한다.
		renamed_file_name = "%d-%s%03d_%s.swf" % (i, key, i - minValue + 1, suffix)
		if (key == 'NUM'):
			renamed_file_name = "%d-%s%02d_%s.swf" % (i, key, i - minValue + 1, suffix)
		#endif	
		if (j % 4 == 0):
			i = i+1
			j=j+1
			rename_full_path = os.path.join(root, renamed_file_name)
			os.rename(fullpath, rename_full_path)
			print '%s is rename to %s' % (item, renamed_file_name)
		#end - if
	#end - for	
if __name__ == '__main__':
	root = "D:/git/flash_korean_novice/resources/ai/verb"
	key = 'V'
	startIndex=321
	print root
	rename_flash_content(root, key, startIndex)
#end-if