如何使用 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學習者快速成長!