How to delete a file or folder?
如何删除Python中的文件或文件夹?
os.remove()
will remove a file.
os.rmdir()
will remove an empty directory.
shutil.rmtree()
will delete a directory and all its contents.
Python Syntax to Delete a file
import os
os.remove("/tmp/<file_name>.txt")
OR
import os
os.unlink("/tmp/<file_name>.txt")
Best Practice:
1. First check whether the file or folder exits or not then only delete that file. This can be achieved in two ways :
a. os.path.isfile("/path/to/file")
b. Use exception handling.
EXAMPLE for 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)
Exception Handling
#!/usr/bin/python
import os
## get input ##
myfile= raw_input("Enter file name to delete : ")
## try to delete file ##
try:
os.remove(myfile)
except OSError, e: ## if failed, report it back to the user ##
print ("Error: %s - %s." % (e.filename,e.strerror))
RESPECTIVE OUTPUT
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 Syntax to delete a folder
shutil.rmtree()
Example for shutil.rmtree()
#!/usr/bin/python
import os
import sys
import shutil
# Get dir 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, e:
print ("Error: %s - %s." % (e.filename,e.strerror))
Use
shutil.rmtree(path[, ignore_errors[, onerror]])
(see complete doc on shutil) and/or
os.remove
and
os.rmdir
(complete doc on os)
链接地址: http://www.djcxy.com/p/1130.html上一篇: 动态加载JavaScript文件
下一篇: 如何删除文件或文件夹?