How to delete a file by extension in Python?

后端 未结 5 1193
傲寒
傲寒 2020-12-15 04:36

I was messing around just trying to make a script that deletes items by \".zip\" extension.

import sys
import os
from os import listdir

test=os.listdir(\"/U         


        
5条回答
  •  甜味超标
    2020-12-15 04:57

    Alternate approach that avoids join-ing yourself over and over: Use glob module to join once, then let it give you back the paths directly.

    import glob
    import os
    
    dir = "/Users/ben/downloads/"
    
    for zippath in glob.iglob(os.path.join(dir, '*.zip')):
        os.remove(zippath)
    

提交回复
热议问题