Last active
January 24, 2024 01:34
-
-
Save qkdxorjs1002/8447e7c389a9dcd3d99626113d99c6e7 to your computer and use it in GitHub Desktop.
정규식 사용 디렉터리 이름 일괄 변경 (01234 -> 1234) 스크립트
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import time | |
import re | |
from datetime import datetime | |
### 디렉터리 경로 | |
# 역슬래시는 이중으로 | |
# 예시) = "C:\\NIA_COMPLETE_labeling\\" | |
sourcePath = "/Users/paragonnov/Documents/org/submit" | |
# 시작 시간 기록 | |
startTime = time.time() | |
exceptionLogPath = datetime.now().strftime("exception-%Y-%m-%d_%H.%M.%S") + ".log" | |
exceptionLog = open(exceptionLogPath, "a", encoding="utf-8") | |
changeLogPath = datetime.now().strftime("change-%Y-%m-%d_%H.%M.%S") + ".log" | |
changeLog = open(changeLogPath, "a", encoding="utf-8") | |
for path, dirs, files in os.walk(sourcePath): | |
for dir in dirs: | |
# RegEx: 정규식 표현으로 앞에 '0'이 포함되고 후행으로 숫자 4자리 포함될 경우 0을 제외한 후행 문자열을 그룹 | |
regexResult = re.search("(?<=0)\d\d\d\d", dir) | |
if not regexResult: | |
continue | |
renamedDir = regexResult.group(0) | |
srcDirPath = path + "/" + dir | |
dstDirPath = path + "/" + renamedDir | |
try: | |
# 이름 변경 | |
os.rename(srcDirPath, dstDirPath) | |
print(srcDirPath) | |
# 변경된 사항 기록 | |
changeLog.write(srcDirPath + "\n Renamed: " + dir + " -> " + renamedDir + "\n") | |
except Exception as e: | |
# 예외 로그에 기록 | |
exceptionLog.write(srcDirPath + "\n err: " + str(e) + "\n") | |
exceptionLog.close() | |
changeLog.close() | |
print("✅ Job is done.\n") | |
print("🔴 Running Time:", round(time.time() - startTime, 2), "\bs") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment