如何删除文件或文件夹?
当前回答
为了避免Éric Araujo评论中强调的TOCTOU问题,您可以捕捉一个异常来调用正确的方法:
def remove_file_or_dir(path: str) -> None:
""" Remove a file or directory """
try:
shutil.rmtree(path)
except NotADirectoryError:
os.remove(path)
因为shutil.rmtree()将只删除目录,os.remove()或os.unlink()将仅删除文件。
其他回答
如果您喜欢编写一段漂亮且可读的代码,我建议使用子流程:
import subprocess
subprocess.Popen("rm -r my_dir", shell=True)
如果你不是软件工程师,那么可以考虑使用Jupyter;您可以简单地键入bash命令:
!rm -r my_dir
传统上,您使用shutil:
import shutil
shutil.rmtree(my_dir)
这是我删除目录的功能。“路径”需要完整的路径名。
import os
def rm_dir(path):
cwd = os.getcwd()
if not os.path.exists(os.path.join(cwd, path)):
return False
os.chdir(os.path.join(cwd, path))
for file in os.listdir():
print("file = " + file)
os.remove(file)
print(cwd)
os.chdir(cwd)
os.rmdir(os.path.join(cwd, path))
import os
folder = '/Path/to/yourDir/'
fileList = os.listdir(folder)
for f in fileList:
filePath = folder + '/'+f
if os.path.isfile(filePath):
os.remove(filePath)
elif os.path.isdir(filePath):
newFileList = os.listdir(filePath)
for f1 in newFileList:
insideFilePath = filePath + '/' + f1
if os.path.isfile(insideFilePath):
os.remove(insideFilePath)
os.remove()删除文件。os.rmdir()删除空目录。shutil.rmtree()删除目录及其所有内容。
Python 3.4+pathlib模块中的路径对象还公开了以下实例方法:
pathlib.Path.unlink()删除文件或符号链接。pathlib.Path.rmdir()删除空目录。
对于删除文件:
os.unlink(path, *, dir_fd=None)
or
os.remove(path, *, dir_fd=None)
这两个函数在语义上是相同的。此函数用于删除文件路径。若路径不是文件,而是目录,则引发异常。
删除文件夹:
shutil.rmtree(path, ignore_errors=False, onerror=None)
or
os.rmdir(path, *, dir_fd=None)
为了删除整个目录树,可以使用shutil.rmtree()。os.rmdir仅在目录为空且存在时有效。
对于向父级递归删除文件夹:
os.removedirs(name)
它使用self删除每个空的父目录,直到父目录包含一些内容
例如,如果目录为空,os.removedirs('abc/xyz/pqr')将按“abc/xyz/pqr”、“abc/xy z”和“abc”的顺序删除目录。
有关更多信息,请查看官方文档:os.unlink、os.remove、os.rmdir、shutil.rmtree、os.removedirs
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象