How to delete a file by extension in Python?

后端 未结 5 1176
傲寒
傲寒 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))
    
    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-15 04:59

    Prepend the directory to the filename

    os.remove("/Users/ben/downloads/" + item)
    

    EDIT: or change the current working directory using os.chdir.

    0 讨论(0)
  • 2020-12-15 05:02
    origfolder = "/Users/ben/downloads/"
    test = os.listdir(origfolder)
    
    for item in test:
        if item.endswith(".zip"):
            os.remove(os.path.join(origfolder, item))
    

    The dirname is not included in the os.listdir output. You have to attach it to reference the file from the list returned by said function.

    0 讨论(0)
  • 2020-12-15 05:04

    For this operation you need to append the file name on to the file path so the command knows what folder you are looking into.

    You can do this correctly and in a portable way in python using the os.path.join command.
    For example:

    import sys
    import os
    
    directory = "/Users/ben/downloads/"
    test = os.listdir( directory )
    
    for item in test:
        if item.endswith(".zip"):
            os.remove( os.path.join( directory, item ) )
    
    0 讨论(0)
提交回复
热议问题