2008-10-09 90 views
250

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

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

+21

尽管`shutil.rmtree()`可以删除文件夹内容,它也会删除该文件夹。如果文件夹具有特殊权限或所有者位设置,则删除后重新创建文件夹将无济于事。 – Rockallite 2014-07-19 20:28:31

回答

237

更新为仅删除文件并使用注释中建议的os.path.join()方法。如果您还想删除子目录,请取消注释elif语句。

import os, shutil 
folder = '/path/to/folder' 
for the_file in os.listdir(folder): 
    file_path = os.path.join(folder, the_file) 
    try: 
     if os.path.isfile(file_path): 
      os.unlink(file_path) 
     #elif os.path.isdir(file_path): shutil.rmtree(file_path) 
    except Exception as e: 
     print(e) 
+1

我试图没有if语句,但我得到“错误5:访问被拒绝”。该文件夹位于Windows 7中,并且每个人都拥有安全权限的完全访问权限。 – Pitto 2012-05-16 15:54:04

+4

这不会删除* all *文件夹中的所有内容,如果删除if,则只会生成文件,符号链接和*空*目录。相反,添加一个`else`子句并使用`rmtree`作为目录(根据user609215的代码)。 – Ian 2012-06-24 16:58:29

+8

删除if语句将不起作用。 os.unlink/remove不能在目录上工作,为空或不是。要处理目录,请添加 `elif os.path.isdir(file_path): shutil。rmtree(FILE_PATH)` – 2014-01-08 23:59:41

8

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

os.listdir()不从目录文件区分开,你很快就会进入试图取消这些麻烦。有一个很好的例子,使用os.walk()递归地删除一个目录here,并提示如何使其适应您的情况。

163

尝试shutil模块

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

说明:shutil.rmtree(path, ignore_errors=False, onerror=None)

文档字符串:递归删除 目录树。

如果ignore_errors设置,错误被忽略 ;否则,如果onerror设置, 它被称为与 参数(func, path, exc_info)其中 funcos.listdiros.remove,或 os.rmdir来处理错误;路径是导致它失败的那个函数的参数;和 exc_info是由 sys.exc_info()返回的元组。如果ignore_errors是 虚假和onerrorNone,一个 异常。

+124

这不仅会删除内容,还会删除文件夹本身。我不认为这是问题所在。 – 2009-07-01 17:14:02

+40

所以只能删除什么在它之下:shutil.rmtree( '/路径/到/文件夹/ *') – 2010-09-03 09:16:59

+58

比较晚了这里的游戏,但'shutil.rmtree( '/路径/到/文件夹/ *')没有按`不起作用,至少在OSX和Windows XP上(Python 2.6.6)。在OSX上python 2.6.6报告“没有这样的文件或目录”。我在Window上收到类似的错误。 – 2011-02-03 22:44:55

60

扩大对mhawke的答案,这是我实施的。它删除文件夹的所有内容,但不删除文件夹本身。在Linux上使用文件,文件夹和符号链接进行测试,也应该可以在Windows上运行。对于在删除所有文本文件/YOU/PATH/*.txt:

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)) 
111

你可以简单地这样做:

import os 
import glob 

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

您可以科西嘉在您路径使用其他过滤器,用于为例目录。

41

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

使用散步的建议解决方案不起作用,因为它使用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): 
     os.unlink(file_object_path) 
    else: 
     shutil.rmtree(file_object_path) 
7

这是唯一的答案,到目前为止,其中:

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

代码:

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

正如许多其他的答案,这并不试图调整权限,使去除的文件/目录。

5
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 
[os.remove(i) if os.path.isfile(i) or os.path.islink(i) else shutil.rmtree(i) for i in contents] 

以前的评论还提到在Python 3.5+中使用os.scandir。例如:

import os 
import shutil 

with os.scandir(target_dir) as entries: 
    for entry in entries: 
     if entry.is_file() or entry.is_symlink(): 
      os.remove(entry.path) 
     elif entry.is_dir(): 
      shutil.rmtree(entry.path) 
6

我知道这是一个古老的线程,但我发现一些有趣的东西从官方网站的蟒蛇。只是为了共享删除目录中所有内容的另一个想法。因为使用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)) 
5

我用来解决这个问题是这样的:

import shutil 
import os 

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

作为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))) 
5

还没有她的解决方案:

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

注:万一有人下来投我的回答,我有事情要在这里解释。

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

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

它解决了其不被其他应答者解决了几个问题:

  • 它能够正确处理符号链接,包括符号链接(这将通过os.path.isdir()测试,如果它链接到一个上没有要求shutil.rmtree()目录;即使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") 
-3

这应该做的伎俩只是使用的操作系统模块列表,然后删除!

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

工作对我来说,任何问题都让我知道!

0

答案有限,具体情况: 假设你要删除的文件,同时maintainig子文件夹树,你可以使用一个递归算法:

import os 

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

recursively_remove_files(my_directory) 

也许稍微偏离主题,但我认为很多会发现它很有用

1

我解决了与rmtree makedirs之间添加time.sleep()之间的错误问题。

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

time.sleep(.5) 

os.makedirs(folder_location, 0o777) 
相关问题