如何删除文件夹的内容?

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

当前的项目是Windows,但我也希望看到*nix。

844962 次浏览
import os, shutil
folder = '/path/to/folder'
for filename in os.listdir(folder):
file_path = os.path.join(folder, filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print('Failed to delete %s. Reason: %s' % (file_path, e))

为此,您可能最好使用os.walk()

os.listdir()不能区分文件和目录,你很快就会在试图解除关联时遇到麻烦。有一个使用os.walk()递归删除目录这里的好例子,并提示如何使其适应你的情况。

您可以使用shutil.rmtree删除文件夹本身及其所有内容:

import shutil
shutil.rmtree('/path/to/folder')
shutil.rmtree(path, ignore_errors=False, onerror=None)


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

扩展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))

你可以简单地这样做:

import os
import glob


files = glob.glob('/YOUR/PATH/*')
for f in files:
os.remove(f)

当然,您可以在路径中使用其他过滤器,例如: /YOU/PATH/*. txt用于删除目录中的所有文本文件。

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

使用walk的建议解决方案不起作用,因为它使用rmtree删除文件夹,然后可能会尝试在这些文件夹中以前的文件上使用os.unlink。这会导致错误。

发布的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)

这个:

  • 删除所有符号链接
    • 死链接
    • 链接到目录
    • 文件链接
  • 删除子目录
  • 不删除父目录

代码:

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

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

在Python 3.6+中使用os.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]

我知道这是一个古老的线程,但我从python的官方网站上发现了一些有趣的东西。只是为了分享另一个删除目录中所有内容的想法。因为我在使用shutil.rmtree()时遇到了一些授权问题,我不想删除目录并重新创建它。原始地址是http://docs.python.org/2/library/os.html#os.walk。希望能帮助到某人。

def emptydir(top):
if(top == '/' or top == "\\"): return
else:
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))

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

import shutil
import os


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

作为oneliner:

import os


# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )


# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )

一个更健壮的文件和目录解决方案是(2.7):

def rm(f):
if os.path.isdir(f): return os.rmdir(f)
if os.path.isfile(f): return os.unlink(f)
raise TypeError, 'must be either file or directory'


map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )

另一种解决方案:

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

注意:如果有人否决了我的答案,我有一些事情要解释。

  1. 每个人都喜欢简短的答案。然而,有时现实并不是那么简单。
  2. 回到我的回答。我知道shutil.rmtree()可以用来删除目录树。我在自己的项目中多次使用它。但是你必须意识到目录本身也将被shutil.rmtree()删除。虽然这对某些人来说可能是可以接受的,但对于删除文件夹的内容(没有副作用)来说,这不是一个有效的答案。
  3. 我举个副作用的例子。假设你有一个包含定制所有者和模式位的目录,其中有很多内容。然后你用shutil.rmtree()删除它,然后用os.mkdir()重建它。你会得到一个包含默认(继承的)所有者和模式位的空目录。虽然你可能有权删除内容甚至目录,但你可能无法在目录上设置原始所有者和模式位(例如你不是超级用户)。
  4. 最后,耐心阅读代码。它又长又丑(在眼前),但被证明是可靠和高效的(在使用中)。

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

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

  • 它正确处理符号链接,包括不在符号链接上调用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")

这应该只是使用操作系统模块来列出然后删除的技巧!

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

为我工作,任何问题让我知道!

对于有限的特定情况的答案: 假设您想在维护子文件夹树时删除文件,您可以使用递归算法:

import os


def recursively_remove_files(f):
if os.path.isfile(f):
os.unlink(f)
elif os.path.isdir(f):
for fi in os.listdir(f):
recursively_remove_files(os.path.join(f, fi))


recursively_remove_files(my_directory)

也许有点离题,但我想很多人会发现它很有用

我通过在rmtreemakedirs之间添加time.sleep()解决了问题:

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


time.sleep(.5)


os.makedirs(folder_location, 0o777)

如果你使用的是*nix系统,为什么不使用system命令呢?

import os
path = 'folder/to/clean'
os.system('rm -rf %s/*' % path)

使用下面的方法删除目录的内容,而不是目录本身:

import os
import shutil


def remove_contents(path):
for c in os.listdir(path):
full_path = os.path.join(path, c)
if os.path.isfile(full_path):
os.remove(full_path)
else:
shutil.rmtree(full_path)

要删除目录及其子目录中的所有文件,而不删除文件夹本身,只需执行以下操作:

import os
mypath = "my_folder" #Enter your path here
for root, dirs, files in os.walk(mypath, topdown=False):
for file in files:
os.remove(os.path.join(root, file))


# Add this block to remove folders
for dir in dirs:
os.rmdir(os.path.join(root, dir))


# Add this line to remove the root folder at the end
os.rmdir(mypath)

我很惊讶没有人提到令人敬畏的pathlib来完成这项工作。

如果您只想删除目录中的文件,它可以是oneliner

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)

非常直观的方法:

import shutil, os




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




remove_folder_contents('/path/to/folder')

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

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

嗯,我认为此代码正在工作。它不会删除文件夹,您可以使用此代码删除具有特定扩展名的文件。

import os
import glob


files = glob.glob(r'path/*')
for items in files:
os.remove(items)

我不得不从单个父目录中的3个单独文件夹中删除文件:

directory
folderA
file1
folderB
file2
folderC
file3

这个简单的代码对我起了作用:(我在Unix上)

import os
import glob


folders = glob.glob('./path/to/parentdir/*')
for fo in folders:
file = glob.glob(f'{fo}/*')
for f in file:
os.remove(f)

希望这有帮助。

要删除我使用的文件夹a中的所有文件:

import os
for i in os.listdir():
os.remove(i)

使用此功能

import glob


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


truncate('/my/path')