Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách đổi tên nhiều file đệ quy bằng Python?


Dùng os.walk duyệt đệ quy thư mục và os.rename đổi tên file.

Ví dụ

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)

Dùng hàm như sau:

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

Sẽ tìm tất cả file đệ quy trong thư mục và sub-thư mục, thay IMG thành Image. Bạn sửa hàm cho phù hợp nhu cầu.