DBILITY

python file rename, copy etc. 본문

python

python file rename, copy etc.

DBILITY 2021. 8. 19. 12:22
반응형

특정 디렉토리의 파일 목록을 조회, 이름변경, 복사를 해봤다.

os, shutil을 사용.

문자열 앞에 r이나 R을 붙이면 백슬래시(\)가 문자로 인식된다.즉, Escape문자로 인식하지 않는다.

import os
import shutil
import uuid

# current directory
print(os.getcwd())

# A Python raw string is a normal string, prefixed with a r or R.
# This treats characters such as backslash (‘\’) as a literal character.
# This also means that this character will not be treated as a escape character.
file_path: str = r'.\test'
# change directory
os.chdir(file_path)
# list up current directory
file_list: list = os.listdir('./')

for file_name in file_list:
    print(file_name)
    # file rename
    if file_name.endswith('.txt'):
        os.rename(file_name, f'test{file_name}')
    # file copy
    if file_name.endswith('.txt'):
        rand_file_name: str = str(uuid.uuid4())
        shutil.copy(f'test{file_name}', f'{rand_file_name}test{file_name}')
반응형
Comments