· Mar 31, 2020 · Edited: Mar 31, 2020
有以下几种方法:
os.remove():删除一个文件
os.rmdir():删除一个空文件夹,否则抛出OSError异常
shutil.rmtree():递归删除一个文件夹以及下面的所有内容
#!/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)
如果Python是3.4以上,还可以用pathlib里面的Path方法:
pathlib.Path.unlink():删除一个文件或者链接
pathlib.Path.rmdir():删除一个空文件夹
#!/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))
有以下几种方法:
os.remove():删除一个文件
os.rmdir():删除一个空文件夹,否则抛出OSError异常
shutil.rmtree():递归删除一个文件夹以及下面的所有内容
#!/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)
如果Python是3.4以上,还可以用pathlib里面的Path方法:
pathlib.Path.unlink():删除一个文件或者链接
pathlib.Path.rmdir():删除一个空文件夹
#!/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))