例子1:
完成tab到4个空格的转换功能.
#! /usr/bin/env python
# -*- coding:utf8 -*-
import sys
import re
import os
def main():
filename = sys.argv[1]
#打开文件
fr = open(filename, 'r')
fw = open(filename+'.bak', 'wx')
#读取文件的每一行
for line in fr.readlines():
line=re.sub('\t', ' ', line)
fw.write(line)
os.remove(filename)
os.rename(filename+'.bak', filename)
os.chmod(filename, 0700)
if __name__ == '__main__':
main()
例子2:
完成对某目录下所有文件的字符串查找功能。
#!/usr/bin/env python
# -*- coding:utf8 -*-
import os,sys
import re
from stat import *
filename='.'
def main(filename):
dirs = os.listdir(filename)
for f in dirs:
f = os.path.join(filename,f);
st = os.stat(f)
if(S_ISDIR(st[ST_MODE])):
main(f)
if not S_ISREG(st[ST_MODE]):
continue;
file=open(f,'r')
for words in file.readlines():
if re.search(sys.argv[1], words):
print file.name, " : ", words,
file.close()
if __name__ == '__main__':
if(len(sys.argv) == 3):
filename=sys.argv[2]
main(filename)
阅读(1315) | 评论(0) | 转发(0) |