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

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


当前回答

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()递归删除目录的好例子,并提示了如何使其适应您的环境。

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

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

扩展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 sh
sh.rm(sh.glob('/path/to/folder/*'))

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

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)