如何在 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))

更新於: 2019 年 12 月 12 日

3K+ 瀏覽

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.