Python을 사용하여 디렉터리에 있는 여러 파일의 이름을 바꾸는 방법

Mary-Kate Olsen
풀어 주다: 2024-10-24 04:41:30
원래의
957명이 탐색했습니다.

How to Rename Multiple Files in a Directory Using Python

Python을 사용하여 디렉터리의 여러 파일 이름 바꾸기

한 디렉터리의 여러 파일 이름을 바꾸는 작업은 수동으로 수행할 경우 지루한 작업이 될 수 있습니다. 그러나 Python은 이 프로세스를 자동화하여 더욱 효율적이고 정확하게 만드는 여러 옵션을 제공합니다.

접근 방식:

os.path.split 사용

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    # Split the filename and extension
    filename, ext = os.path.splitext(file)

    # Modify the filename
    modified_filename = filename.split('_')[1]

    # Combine the modified filename with the extension
    new_file = modified_filename + ext

    # Rename the file
    os.rename(os.path.join(folder, file), os.path.join(folder, new_file))
로그인 후 복사

문자열 조작 사용:

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    if file.startswith('CHEESE_'):
        # Remove 'CHEESE_' from the filename
        new_file = file[7:]

        # Rename the file
        os.rename(os.path.join(folder, file), os.path.join(folder, new_file))
로그인 후 복사

os.rename 사용

import os
folder = 'dir'
files = os.listdir(folder)

for file in files:
    if file.startswith('CHEESE_'):
        # Get the new filename
        new_file = file[7:]

        # Use os.rename() to change the filename
        os.rename(os.path.join(folder, file), os.path.join(folder, new_file))
로그인 후 복사

모두 이러한 접근 방식을 사용하면 디렉터리에서 파일 이름을 바꾸고 "CHEESE_" 접두사를 제거하고 원래 확장자를 유지하는 원하는 결과를 얻을 수 있습니다.

위 내용은 Python을 사용하여 디렉터리에 있는 여러 파일의 이름을 바꾸는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!