Python 删除某个路径下所有文件及模块调用注意事项
import os
#from os import path
import sys
#from sys import argv
import shutil
directory = sys.argv[1] # need to add "from sys import argv" but not "import sys" , or else it will display "argv is not defined"#
if os.path.isdir(directory): #return true if the pathname refers to an existing directory#
print "path"+" "+ directory + " " + "is exist!"
filelist = os.listdir(directory) #return a list containing the names of the entries in the direcory#
print filelist
for name in filelist: # try to delete a file, and if it is a folder jump to except to delete folder
try:
os.remove(directory +"/"+ name) # delete files in path "directory"#
except:
print "this is a folder not a file!"
#os.rmdir(directory + "/" + name) # remve(delete) the directory path. only works when the directory is empty
shutil.rmtree(directory +"/"+ name) # delete an entire directory tree.
print "files delete complete!"
else:
print "path"+" "+ directory + " " + "is not exist!"
注意:
1. 这段代码如果在开头部分使用 import sys, 则在应用argv这个模块的时候,要使用directory = os.argv [1], 否则会报“'argv' is not defined ”的错误; 而如果使用from sys import argv 来导入模块, 则可以使用directory = argv[1]。 在编写python 程序的时候,最好有自己的风格,建议是全部采用import sys , 而在应用argv模块的使用,说明清楚该模块是在sys里面的, 即sys.argv的。 同理,用 import os导入os模块时, 在应用isdir(),listdir(), remove()等函数时,也必须说明清楚具体的在那个模块里面, 即os.path.isdir(), os.listdir(), os.remove().
2. 区别os.rmdir()和shutil.rmtree(), 前者只能删除一个空文件夹, 后者是删除整个目录,空目录和有文件的目录均可删除。