如何在Python中删除文件或文件夹?
[os.remove()
删除文件。
$ pip install pathlib2
或
from os import rmdir
rmdir(join(expanduser('~'), 'directory'))
:并且,如果您不是软件工程师,那么可以考虑使用Jupyter;您可以简单地输入bash命令:
exception handling.
shutil.rmtree()
#!/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
方法:
如何删除Python中的文件或文件夹?
>>> 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'
>>> directory_path.exists()
False
要删除目录中的所有文件夹