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

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


当前回答

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

其他回答

使用这个函数

import os
import glob

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

truncate('/my/path')

删除文件夹a中的所有文件:

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

你可以使用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
import glob

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

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

还有另一个解决方案:

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