Remove all files in a directory

前端 未结 13 2079
小蘑菇
小蘑菇 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 19:54

    Bit of a hack but if you would like to keep the directory, the following can be used.

    import os
    import shutil
    shutil.rmtree('/home/me/test') 
    os.mkdir('/home/me/test')
    
    0 讨论(0)
  • 2020-12-23 19:54
    #python 2.7
    import tempfile
    import shutil
    import exceptions
    import os
    
    def TempCleaner():
        temp_dir_name = tempfile.gettempdir()
        for currentdir in os.listdir(temp_dir_name):
            try:
               shutil.rmtree(os.path.join(temp_dir_name, currentdir))
            except exceptions.WindowsError, e:
                print u'Не удалось удалить:'+ e.filename
    
    0 讨论(0)
  • 2020-12-23 19:56

    star is expanded by Unix shell. Your call is not accessing shell, it's merely trying to remove a file with the name ending with the star

    0 讨论(0)
  • 2020-12-23 19:58

    Another way I've done this:

    os.popen('rm -f ./yourdir')
    
    0 讨论(0)
  • 2020-12-23 20:04

    shutil.rmtree() for most cases. But it doesn't work for in Windows for readonly files. For windows import win32api and win32con modules from PyWin32.

    def rmtree(dirname):
        retry = True
        while retry:
            retry = False
            try:
                shutil.rmtree(dirname)
            except exceptions.WindowsError, e:
                if e.winerror == 5: # No write permission
                    win32api.SetFileAttributes(dirname, win32con.FILE_ATTRIBUTE_NORMAL)
                    retry = True
    
    0 讨论(0)
  • 2020-12-23 20:05

    Please see my answer here:

    https://stackoverflow.com/a/24844618/2293304

    It's a long and ugly, but reliable and efficient solution.

    It resolves a few problems which are not addressed by the other answerers:

    • It correctly handles symbolic links, including not calling shutil.rmtree() on a symbolic link (which will pass the os.path.isdir() test if it links to a directory).
    • It handles read-only files nicely.
    0 讨论(0)
提交回复
热议问题