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

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


当前回答

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

建议的使用walk的解决方案不能工作,因为它使用rmtree删除文件夹,然后可能会尝试使用os。解除之前在这些文件夹中的文件的链接。这将导致一个错误。

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

其他回答

使用这个函数

import os
import glob

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

truncate('/my/path')

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

希望这能有所帮助。

我通过添加time.sleep()来解决rmtree makedirs的问题:

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

time.sleep(.5)

os.makedirs(folder_location, 0o777)

这应该做的技巧,只是使用OS模块列出,然后删除!

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

为我工作过,有任何问题请告诉我!

非常直观的方法:

import shutil, os


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


remove_folder_contents('/path/to/folder')