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

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


当前回答

注:以防有人对我的答案投了反对票,我在这里有一些事情要解释。

Everyone likes short 'n' simple answers. However, sometimes the reality is not so simple. Back to my answer. I know shutil.rmtree() could be used to delete a directory tree. I've used it many times in my own projects. But you must realize that the directory itself will also be deleted by shutil.rmtree(). While this might be acceptable for some, it's not a valid answer for deleting the contents of a folder (without side effects). I'll show you an example of the side effects. Suppose that you have a directory with customized owner and mode bits, where there are a lot of contents. Then you delete it with shutil.rmtree() and rebuild it with os.mkdir(). And you'll get an empty directory with default (inherited) owner and mode bits instead. While you might have the privilege to delete the contents and even the directory, you might not be able to set back the original owner and mode bits on the directory (e.g. you're not a superuser). Finally, be patient and read the code. It's long and ugly (in sight), but proven to be reliable and efficient (in use).


这里有一个冗长而丑陋,但可靠而有效的解决方案。

它解决了一些其他答案没有解决的问题:

它正确地处理符号链接,包括不对符号链接调用shutil.rmtree()(如果它链接到一个目录,它将通过os.path.isdir()测试;甚至os.walk()的结果也包含符号链接目录)。 它可以很好地处理只读文件。

下面是代码(唯一有用的函数是clear_dir()):

import os
import stat
import shutil


# http://stackoverflow.com/questions/1889597/deleting-directory-in-python
def _remove_readonly(fn, path_, excinfo):
    # Handle read-only files and directories
    if fn is os.rmdir:
        os.chmod(path_, stat.S_IWRITE)
        os.rmdir(path_)
    elif fn is os.remove:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


def force_remove_file_or_symlink(path_):
    try:
        os.remove(path_)
    except OSError:
        os.lchmod(path_, stat.S_IWRITE)
        os.remove(path_)


# Code from shutil.rmtree()
def is_regular_dir(path_):
    try:
        mode = os.lstat(path_).st_mode
    except os.error:
        mode = 0
    return stat.S_ISDIR(mode)


def clear_dir(path_):
    if is_regular_dir(path_):
        # Given path is a directory, clear its content
        for name in os.listdir(path_):
            fullpath = os.path.join(path_, name)
            if is_regular_dir(fullpath):
                shutil.rmtree(fullpath, onerror=_remove_readonly)
            else:
                force_remove_file_or_symlink(fullpath)
    else:
        # Given path is a file or a symlink.
        # Raise an exception here to avoid accidentally clearing the content
        # of a symbolic linked directory.
        raise OSError("Cannot call clear_dir() on a symbolic link")

其他回答

使用操作系统。Python 3.6+中的scandir和上下文管理器协议:

import os
import shutil

with os.scandir(target_dir) as entries:
    for entry in entries:
        if entry.is_dir() and not entry.is_symlink():
            shutil.rmtree(entry.path)
        else:
            os.remove(entry.path)

Python的早期版本:

import os
import shutil

# Gather directory contents
contents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)]

# Iterate and remove each item in the appropriate manner
[shutil.rmtree(i) if os.path.isdir(i) and not os.path.islink(i) else os.remove(i) for i in contents]

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

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

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

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

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

使用这个函数

import os
import glob

def truncate(path):
    files = glob.glob(path+'/*.*')
    for f in files:
        os.remove(f)

truncate('/my/path')

扩展mhawke的回答,这是我所实现的。它删除文件夹的所有内容,但不删除文件夹本身。在Linux上测试了文件、文件夹和符号链接,应该也能在Windows上运行。

import os
import shutil

for root, dirs, files in os.walk('/path/to/folder'):
    for f in files:
        os.unlink(os.path.join(root, f))
    for d in dirs:
        shutil.rmtree(os.path.join(root, d))