设为首页 加入收藏

TOP

Python 删除某个路径下所有文件及模块调用注意事项
2014-11-24 02:50:54 来源: 作者: 【 】 浏览:0
Tags:Python 删除 某个 路径 所有 文件 模块 调用 注意事项

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(), 前者只能删除一个空文件夹, 后者是删除整个目录,空目录和有文件的目录均可删除。


推荐阅读:


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Android短信转发默认不需要转发号.. 下一篇Android自定义图形,图形的拼接、..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: