如何在Python中删除本地文件夹的内容?

目前的项目是Windows,但我也想看到*nix。


当前回答

还有另一个解决方案:

import sh
sh.rm(sh.glob('/path/to/folder/*'))

其他回答

使用rmtree并重新创建文件夹可以工作,但是我在删除并立即在网络驱动器上重新创建文件夹时遇到了错误。

建议的使用walk的解决方案不能工作,因为它使用rmtree删除文件夹,然后可能会尝试使用os。解除之前在这些文件夹中的文件的链接。这将导致一个错误。

发布的glob解决方案还将尝试删除非空文件夹,从而导致错误。

我建议你使用:

folder_path = '/path/to/folder'
for file_object in os.listdir(folder_path):
    file_object_path = os.path.join(folder_path, file_object)
    if os.path.isfile(file_object_path) or os.path.islink(file_object_path):
        os.unlink(file_object_path)
    else:
        shutil.rmtree(file_object_path)

你可以使用shutil.rmtree删除文件夹本身,以及它的所有内容:

import shutil
shutil.rmtree('/path/to/folder')

shutil。rmtree(path, ignore_errors=False, onerror=None) 删除整个目录树;Path必须指向目录(但不是指向目录的符号链接)。如果ignore_errors为true,移除失败导致的错误将被忽略;如果为false或省略,则通过调用onerror指定的处理程序来处理此类错误,如果省略,则会引发异常。

非常直观的方法:

import shutil, os


def remove_folder_contents(path):
    shutil.rmtree(path)
    os.makedirs(path)


remove_folder_contents('/path/to/folder')

我通过添加time.sleep()来解决rmtree makedirs的问题:

if os.path.isdir(folder_location):
    shutil.rmtree(folder_location)

time.sleep(.5)

os.makedirs(folder_location, 0o777)

删除文件夹中所有文件/删除所有文件的最简单方法

import os
files = os.listdir(yourFilePath)
for f in files:
    os.remove(yourFilePath + f)