使用 Python 重新命名多個檔案


若要在 Python 中重新命名檔案,請使用 rename() 方法os 模組rename() 方法的引數是源地址(舊名稱)和目標地址(新名稱)。

安裝和匯入 OS 模組

若要安裝 OS 模組 −

pip install os

若要匯入 −

import os

使用 rename() 方法重新命名多個檔案

rename() 方法可以輕鬆地用於重新命名多個檔案 −

示例

import os # Function to rename multiple files def main(): i = 0 path="E:/amit/" for filename in os.listdir(path): my_dest ="new" + str(i) + ".jpg" my_source =path + filename my_dest =path + my_dest # rename() function will # rename all the files os.rename(my_source, my_dest) i += 1 # Driver Code if __name__ == '__main__': # Calling main() function main()

以上程式碼會重新命名資料夾“amit”中的所有檔案。

重新命名特定多個檔案

在 Python 中,可以選擇資料夾中要重新命名的多個檔案。

import os filesRename = ['demo_1.txt', 'demo_2.txt', 'demo_3.txt',] folder = r"E:\docs" # Iterate for file in os.listdir(folder): # Checking if the file is present in the list if file in filesRename: oldName = os.path.join(folder, file) n = os.path.splitext(file)[0] b = n + '_new' + '.txt' newName = os.path.join(folder, b) # Rename the file os.rename(oldName, newName) res = os.listdir(folder) print(res)

以上程式碼只會重新命名 docs 資料夾中的 3 個檔案。

更新時間: 2023 年 8 月 24 日

5 萬次以上瀏覽

開啟您的 職業生涯

完成課程即可獲得認證

開始使用
廣告
© . All rights reserved.