DL(Deep-Learning)/Python 기초

[Python] 파일 이름 변경하기

AI 그게 뭔데 2022. 1. 26. 22:40

폴더 안에 있는 파일의 이름을 변경하고 싶을 때, os모듈의 rename을 사용하면 쉽게 변경이 가능하다.

 

1. 폴더 안의 파일 이름을 가져온다.

import os

# 주어진 디렉토리에 있는 항목들의 이름을 담고 있는 리스트를 반환합니다.
# 리스트는 임의의 순서대로 나열됩니다.
file_path = 'Your Path' # 경로 지정
file_names = os.listdir(file_path)
files = sorted(file_names) # 파일 이름 정렬

 

 

2. 파일 이름을 변경, 저장한다.

for name in files:
    src = os.path.join(file_path, name)
    dst = name.replace('.dcm', '') # 변경하고 싶은 이름 지정
    dst = os.path.join(file_path, dst)
    os.rename(src, dst)

 

 os.rename(src, dst) 메서드는 파일 또는 디렉토리(폴더) src의 이름을 dst로 변경해준다.

 

 

# 임의의 숫자로 변경하고 싶을때

i = 1
for name in file_names:
    src = os.path.join(file_path, name)
    dst = str(i) + '.jpg'
    dst = os.path.join(file_path, dst)
    os.rename(src, dst)
    i += 1