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(), 前者只能刪除一個空文件夾, 後者是刪除整個目錄,空目錄和有文件的目錄均可刪除。