如何用 Python 刪除目錄中的多個檔案?


你可以在 os 模組中使用函式刪除單個檔案或單個空資料夾。

示例

例如,如果你想刪除一個檔案 my_file.txt,

>>> import os
>>> os.remove('my_file.txt')

os.remove 的引數可以是絕對路徑或相對路徑。

要刪除多個檔案,只需迴圈你的檔案列表並使用上述函式。如果你想刪除包含你要刪除的所有檔案的資料夾,你可以按如下方式刪除該資料夾

>>> import shutil
>>> shutil.rmtree('my_folder')

示例

你還可以使用正則表示式刪除匹配模式的檔案。例如,

import os, re, os.path
pattern = "^your_regex_here$"
mypath = "my_folder"
for root, dirs, files in os.walk(mypath):
    for file in filter(lambda x: re.match(pattern, x), files):
        os.remove(os.path.join(root, file))

更新於:12-12-2019

3000+ 瀏覽

開啟你的職業生涯

完成課程即可獲得認證

立即開始
廣告
© . All rights reserved.