How to delete a file by extension in Python?

后端 未结 5 1192
傲寒
傲寒 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:41

    You can set the path in to a dir_name variable, then use os.path.join for your os.remove.

    import os
    
    dir_name = "/Users/ben/downloads/"
    test = os.listdir(dir_name)
    
    for item in test:
        if item.endswith(".zip"):
            os.remove(os.path.join(dir_name, item))
    

提交回复
热议问题