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

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


当前回答

我知道这是一个老线程,但我从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))

其他回答

我很惊讶没有人提到做这项工作的很棒的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)

如果您正在使用*nix系统,为什么不利用system命令呢?

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

使用操作系统。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指定的处理程序来处理此类错误,如果省略,则会引发异常。

我必须从一个父目录中的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)

希望这能有所帮助。