- 论坛徽章:
- 0
|
用python写个小程序:
#!/usr/bin/python
#filename: dir.py
import os
from os.path import join
from os import chdir,remove
for root,dirs,files in os.walk('/home/lsj'):
for file in files:
if file[-1:]=='~'or file[-4:]=='.swp':
print 'delete file is:',join(root,file)
chdir(root)
remove(file)
print 'Program Finish'其实在遍历文件的时候可以采用另外一个函数:walk(),不过我在python2.5的手册中查询时发现最后还有一个提示信息:
Note: The newer
os
.walk() generator supplies
similar functionality and can be easier to use.所以嘛就不用它了哟,换成os.walk()哈。这两个函数都是很方便的用来扫描目录,而不需要自己动手去写。还需要注意一点的时,在删除目录的时候,一是需要文件的绝对路径,二是需要切换到这个目录中去,要不然python就会提示:
raceback (most recent call last):
File "./dir.py", line 12, in ?
remove(file)
OSError: [Errno 2] No such file or directory: 'Main.cpp~'
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/80381/showart_1218101.html |
|