Remove all files in a directory

前端 未结 13 2081
小蘑菇
小蘑菇 2020-12-23 19:19

Trying to remove all of the files in a certain directory gives me the follwing error:

OSError: [Errno 2] No such file or directory: \'/home/me/test/*\

相关标签:
13条回答
  • 2020-12-23 20:06

    This will get all files in a directory and remove them.

    import os
    
    BASE_DIR = os.path.dirname(os.path.abspath(__file__))
    dir = os.path.join(BASE_DIR, "foldername")
    
    for root, dirs, files in os.walk(dir):
      for file in files:
        path = os.path.join(dir, file)
        os.remove(path)
    
    0 讨论(0)
  • 2020-12-23 20:06

    To Removing all the files in folder.

    import os
    import glob
    
    files = glob.glob(os.path.join('path/to/folder/*'))
    files = glob.glob(os.path.join('path/to/folder/*.csv')) // It will give all csv files in folder
    for file in files:
        os.remove(file)
    
    0 讨论(0)
  • 2020-12-23 20:08

    Because the * is a shell construct. Python is literally looking for a file named "*" in the directory /home/me/test. Use listdir to get a list of the files first and then call remove on each one.

    0 讨论(0)
  • 2020-12-23 20:08

    Although this is an old question, I think none has already answered using this approach:

    # python 2.7
    import os
    
    d='/home/me/test'
    filesToRemove = [os.path.join(d,f) for f in os.listdir(d)]
    for f in filesToRemove:
        os.remove(f) 
    
    0 讨论(0)
  • 2020-12-23 20:14

    os.remove doesn't resolve unix-style patterns. If you are on a unix-like system you can:

    os.system('rm '+test)
    

    Else you can:

    import glob, os
    test = '/path/*'
    r = glob.glob(test)
    for i in r:
       os.remove(i)
    
    0 讨论(0)
  • 2020-12-23 20:16

    os.remove will only remove a single file.

    In order to remove with wildcards, you'll need to write your own routine that handles this.

    There are quite a few suggested approaches listed on this forum page.

    0 讨论(0)
提交回复
热议问题