Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Rename ไฟล์หลายไฟล์แบบ Recursive ด้วย Python

ใช้ os.walk เดินหาไฟล์แบบ recursive แล้ว os.rename เปลี่ยนชื่อ

ตัวอย่าง

import os

def replace(folder_path, old, new):
    for path, subdirs, files in os.walk(folder_path):
        for name in files:
            if old.lower() in name.lower():
                file_path = os.path.join(path, name)
                new_name = os.path.join(path, name.lower().replace(old, new))
                os.rename(file_path, new_name)

ใช้งาน:

replace('my_folder', 'IMG', 'Image')

จะหาไฟล์ทั้งหมดในโฟลเดอร์และซับโฟลเดอร์ แล้วแทนที่ "IMG" ด้วย "Image" ปรับแต่งฟังก์ชันได้ตามต้องการ