如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在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)
其他回答
你可以使用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
def truncate(path):
files = glob.glob(path+'/*.*')
for f in files:
os.remove(f)
truncate('/my/path')
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))
我知道这是一个老线程,但我从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))
使用操作系统。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]