如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
如何在Python中删除本地文件夹的内容?
目前的项目是Windows,但我也想看到*nix。
当前回答
这样的:
删除所有符号链接 死链接 指向目录的链接 文件链接 删除子目录 不移除父目录
代码:
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
try:
shutil.rmtree(filepath)
except OSError:
os.remove(filepath)
与许多其他答案一样,这不会尝试调整权限以允许删除文件/目录。
其他回答
使用操作系统。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]
我通过添加time.sleep()来解决rmtree makedirs的问题:
if os.path.isdir(folder_location):
shutil.rmtree(folder_location)
time.sleep(.5)
os.makedirs(folder_location, 0o777)
我很惊讶没有人提到做这项工作的很棒的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)
这样的:
删除所有符号链接 死链接 指向目录的链接 文件链接 删除子目录 不移除父目录
代码:
for filename in os.listdir(dirpath):
filepath = os.path.join(dirpath, filename)
try:
shutil.rmtree(filepath)
except OSError:
os.remove(filepath)
与许多其他答案一样,这不会尝试调整权限以允许删除文件/目录。
你可以使用shutil.rmtree删除文件夹本身,以及它的所有内容:
import shutil
shutil.rmtree('/path/to/folder')
shutil。rmtree(path, ignore_errors=False, onerror=None) 删除整个目录树;Path必须指向目录(但不是指向目录的符号链接)。如果ignore_errors为true,移除失败导致的错误将被忽略;如果为false或省略,则通过调用onerror指定的处理程序来处理此类错误,如果省略,则会引发异常。