If missing_ok is false (the default), FileNotFoundError is raised if the path does not exist.
If missing_ok is true, FileNotFoundError exceptions will be ignored (same behavior as the POSIX rm -f command).
Changed in version 3.8: The missing_ok parameter was added.
最佳实践
首先,检查文件或文件夹是否存在,然后仅删除该文件。这可以通过两种方式实现:
a、 os.path.isfile("/path/to/file")
b、 使用exception handling.
例如os.path.isfile
#!/usr/bin/python
import os
myfile="/tmp/foo.txt"
## If file exists, delete it ##
if os.path.isfile(myfile):
os.remove(myfile)
else: ## Show an error ##
print("Error: %s file not found" % myfile)
异常处理
#!/usr/bin/python
import os
## Get input ##
myfile= raw_input("Enter file name to delete: ")
## Try to delete the file ##
try:
os.remove(myfile)
except OSError as e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename, e.strerror))
各自输出
Enter file name to delete : demo.txt
Error: demo.txt - No such file or directory.
Enter file name to delete : rrr.txt
Error: rrr.txt - Operation not permitted.
Enter file name to delete : foo.txt
删除文件夹的Python语法
shutil.rmtree()
例如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))
使用
(请参阅有关shutil的完整文档)和/或
以及
(关于os的完整文档。)
^{} 删除文件。
^{} 删除空目录。
^{} 删除目录及其所有内容。
Python 3.4+^{} 模块中的^{} 对象还公开了以下实例方法:
^{} 删除文件或符号链接。
^{} 删除空目录。
删除文件的Python语法
或者
或者
pathlibPython版本库>;3.5
Path.unlink(缺少'u ok=False)
用于删除文件或符号链接的取消链接方法。
最佳实践
a、
os.path.isfile("/path/to/file")
b、 使用
exception handling.
例如
os.path.isfile
异常处理
各自输出
删除文件夹的Python语法
例如
shutil.rmtree()
相关问题 更多 >
编程相关推荐