os.remove()删除文件。
os.rmdir()删除一个空目录。
shutil.rmtree()删除目录及其所有内容。
pathlib.Path.unlink()删除文件或符号链接。
pathlib.Path.rmdir()删除空目录。
import os
os.remove("/tmp/<file_name>.txt")要么
import os
os.unlink("/tmp/<file_name>.txt")os.path.isfile("/path/to/file") 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
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))