Friday, April 22, 2011

How to delete all the files in a directory

import os

dirPath = "/home/giu/pyExperiments/toRemove"
fileList = os.listdir(dirPath)
for fileName in fileList:
 os.remove(dirPath+"/"+fileName)

14 comments:

  1. dude, perfect ! thanks for this it really actually works, unlike all the crap over at stackoverflow.

    ReplyDelete
  2. Hey,

    Appreciated.

    A little improved code

    import os

    dirPath = "/home/giu/pyExperiments/toRemove"
    fileList = os.listdir(dirPath)
    [ os.remove(os.path.abspath(os.path.join(dirPath,fileName))) for fileName in fileList ]

    ReplyDelete
    Replies
    1. Hey buddy ! ,
      Your fileList do not works, as it work as a string not as a directory.
      Instead use this:

      [os.remove(os.path.abspath(os.path.join(destination, fileName))) for fileName in os.listdir(destination)

      Delete
  3. Readability in OP is better.

    ReplyDelete
  4. You will get an error if there is a folder in your dirPath. The 'crap' from stackoverflow does actually work:

    for filename in fileList:
    item=os.path.join(dirPath,fileList)
    if os.path.isfile(item):
    os.remove(item)

    ReplyDelete
    Replies
    1. this creates an error, the correct code is:


      for filename in fileList:
      item=os.path.join(dirPath,filename)
      if os.path.isfile(item):
      os.remove(item)

      Delete
  5. gud 1..it helped..:)

    ReplyDelete
  6. Oops... using this code removed ALL dirs now I don;t have the OS
    What can do?

    ReplyDelete
  7. One small tip:
    instead of
    dirPath+"/"+fileName

    I would recommend
    os.path.join(dirPath, fileName), which will insert a forward slash for Unix and Linux users, and a backslash for the Windows guys.

    An alternative just popped into my mind:


    dirPath = 'some/path'


    shutil.rmtree(dirPath)
    os.mkdir(dirPath)

    ReplyDelete
  8. what a wonderful piece of code.. big thanks dude!!

    ReplyDelete
  9. Thank you! Worked perfect for me.

    ReplyDelete
  10. Thanks works perfectly

    ReplyDelete
  11. Well, that was a great help when I was urgent.
    Thank You

    ReplyDelete

Note: Only a member of this blog may post a comment.