如何删除文件或文件夹?

问题描述 投票:1938回答:11

如何在Python中删除文件或文件夹?

python file-io directory delete-file
11个回答
3073
投票

[os.remove()删除文件。


0
投票
用于删除文件:

$ pip install pathlib2


-1
投票
如果您喜欢编写漂亮而易读的代码,我建议使用from os import rmdir rmdir(join(expanduser('~'), 'directory'))

os.removedirs

并且,如果您不是软件工程师,那么可以考虑使用Jupyter;您可以简单地输入bash命令:

232
投票

删除文件的Python语法


73
投票
使用

exception handling.


31
投票
为你们创建一个函数。

shutil.rmtree()


28
投票
您可以使用内置的#!/usr/bin/python import os import sys import shutil # Get directory name mydir= raw_input("Enter directory name: ") ## Try to remove tree; if failed show an error using try...except on screen try: shutil.rmtree(mydir) except OSError as e: print ("Error: %s - %s." % (e.filename, e.strerror)) 模块(需要Python 3.4+,但PyPI上的较早版本存在反向移植:shutil.rmtree(path[, ignore_errors[, onerror]]) shutil)。

要删除文件,有os.remove 方法:


18
投票
如何删除Python中的文件或文件夹?

2
投票
>>> directory_path.rmdir() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "~/anaconda3/lib/python3.6/pathlib.py", line 1270, in rmdir self._accessor.rmdir(self) File "~/anaconda3/lib/python3.6/pathlib.py", line 387, in wrapped return strfunc(str(pathobj), *args) OSError: [Errno 39] Directory not empty: '/home/excelsiora/directory'

2
投票
shutil.rmtree是异步函数,因此,如果您想检查完成时间,可以使用while ... loop

1
投票
删除文件夹中的所有文件

>>> directory_path.exists() False

要删除目录中的所有文件夹
© www.soinside.com 2019 - 2024. All rights reserved.