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

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


当前回答

我以前是这样解决这个问题的:

import shutil
import os

shutil.rmtree(dirpath)
os.mkdir(dirpath)

其他回答

使用操作系统。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]

这样的:

删除所有符号链接 死链接 指向目录的链接 文件链接 删除子目录 不移除父目录

代码:

for filename in os.listdir(dirpath):
    filepath = os.path.join(dirpath, filename)
    try:
        shutil.rmtree(filepath)
    except OSError:
        os.remove(filepath)

与许多其他答案一样,这不会尝试调整权限以允许删除文件/目录。

我很惊讶没有人提到做这项工作的很棒的pathlib。

如果你只想删除一个目录中的文件,它可以是一个联机程序

from pathlib import Path

[f.unlink() for f in Path("/path/to/folder").glob("*") if f.is_file()] 

要递归地删除目录,你可以这样写:

from pathlib import Path
from shutil import rmtree

for path in Path("/path/to/folder").glob("**/*"):
    if path.is_file():
        path.unlink()
    elif path.is_dir():
        rmtree(path)

使用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)

这应该做的技巧,只是使用OS模块列出,然后删除!

import os
DIR = os.list('Folder')
for i in range(len(DIR)):
    os.remove('Folder'+chr(92)+i)

为我工作过,有任何问题请告诉我!