如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
我很惊讶没有人提到做这项工作的很棒的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)
其他回答
作为一个在线人士:
import os
# Python 2.7
map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
# Python 3+
list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) )
一个更健壮的文件和目录的解决方案是(2.7):
def rm(f):
if os.path.isdir(f): return os.rmdir(f)
if os.path.isfile(f): return os.unlink(f)
raise TypeError, 'must be either file or directory'
map( rm, (os.path.join( mydir,f) for f in os.listdir(mydir)) )
使用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)
扩展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 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))
这样的:
删除所有符号链接 死链接 指向目录的链接 文件链接 删除子目录 不移除父目录
代码:
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
try:
shutil.rmtree(filepath)
except OSError:
os.remove(filepath)
与许多其他答案一样,这不会尝试调整权限以允许删除文件/目录。