如何删除文件或文件夹?
当前回答
我个人的偏好是使用pathlib对象——它提供了一种与文件系统交互的更具Python性和更少出错的方式,尤其是在您开发跨平台代码时。
在这种情况下,您可以使用pathlib3x-它提供了最新的(在编写此答案时为Python 3.10.a0)Python路径库,用于Python 3.6或更高版本,以及一些附加功能,如“copy”、“copy2”、“copy tree”和“rmtree”等。。。
它还包装shutil.rmtree:
$> python -m pip install pathlib3x
$> python
>>> import pathlib3x as pathlib
# delete a directory tree
>>> my_dir_to_delete=pathlib.Path('c:/temp/some_dir')
>>> my_dir_to_delete.rmtree(ignore_errors=True)
# delete a file
>>> my_file_to_delete=pathlib.Path('c:/temp/some_file.txt')
>>> my_file_to_delete.unlink(missing_ok=True)
你可以在github或PyPi上找到它
免责声明:我是pathlib3x库的作者。
其他回答
下面是一个同时使用os.remove和shutil.rmtree的健壮函数:
def remove(path):
""" param <path> could either be relative or absolute. """
if os.path.isfile(path) or os.path.islink(path):
os.remove(path) # remove the file
elif os.path.isdir(path):
shutil.rmtree(path) # remove dir and all contains
else:
raise ValueError("file {} is not a file or dir.".format(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)
Use
shutil.rmtree(path[, ignore_errors[, onerror]])
(参见shutil的完整文档)和/或
os.remove
and
os.rmdir
(操作系统的完整文档)
这是我删除目录的功能。“路径”需要完整的路径名。
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))
os.remove()删除文件。os.rmdir()删除空目录。shutil.rmtree()删除目录及其所有内容。
Python 3.4+pathlib模块中的路径对象还公开了以下实例方法:
pathlib.Path.unlink()删除文件或符号链接。pathlib.Path.rmdir()删除空目录。
推荐文章
- 输入对象的datetime。Datetime没有Datetime属性
- numpy数组的Python内存使用情况
- NumPy或Pandas:保持数组类型为整数,同时具有NaN值
- 列表理解条件中的' elif '
- Python的“property”和“attribute”有什么区别?
- 在Python中格式化多行字典的正确方法是什么?
- 向异常添加信息?
- Sphinx autodoc不够自动
- 如何限制Django模型中数值字段的最大值?
- 访问对象内存地址
- 为什么在Python方法中需要显式地有“self”参数?
- 如何升级Windows 10下的Python安装?
- tqdm在Jupyter笔记本重复打印新的进度条
- 如何在for循环中注释类型?
- 如何替换一个Pandas数据框架的字符串列中的文本?