知识点:
(1)isinstance:
isinstance(object, classinfo) 04.判断实例是否是这个类或者object是变量 05. 06.classinfo 是类型(tuple,dict,int,float) 07.判断变量是否是这个类型 08. 09.class objA: 10.pass 11. 12.A = objA() 13.B = 'a','v' 14.C = 'a string' 15. 16.print isinstance(A, objA) 17.print isinstance(B, tuple) 18.print isinstance(C, basestring) 19.输出结果: 20.True 21.True 22.True(2)difflib:字符串的比较模块
(3)fnmatch:匹配文件名或字符串
(4)python walk:os.walk(’path’),该函数返回一个列表,列表的每个元素是一个三元组,三元组里第一个元素是path下的目录(包括path),第二个元素为该目录下的所有目录名列表,第三个元素为该目录下所有文件名的列表。看到网上有删除.cvs目录的代码,自己也写了一个删除.svn的脚本:
#!/usr/bin/python import os, sys, shutil; def remove_svn(path): for root,dirs,files in os.walk(path): for dir in dirs: if dir == ".svn": shutil.rmtree(os.path.join(root,dir)) if len(sys.argv) <= 1: print "usage: ./remove_svn path" else: remove_svn(sys.argv[1])
以上功能中值得说明的其他几个函数:
1. shutil.rmtree(path)这个函数删除非空目录,它和os.rmdir(path)的区别在于os.rmdir只能删除空目录
2. os.path.join(path1, path2),该函数将两个路径合成一个路径,第一个路径path1是第二个路径path2的父目录
3. sys.argv是命令行参数列表,第一个参数默认为程序名,第二个开始才是真正的参数
re.sub用于替换字符串中的匹配项。下面一个例子将字符串中的空格 ' ' 替换成 '-' :
import re text = "JGood is a handsome boy, he is cool, clever, and so on..." print re.sub(r'\s+', '-', text)
re.sub的函数原型为:re.sub(pattern, repl, string, count)
其中第二个函数是替换后的字符串;本例中为'-'
第四个参数指替换个数。默认为0,表示每个匹配项都替换。
re.sub还允许使用函数对匹配项的替换进行复杂的处理。如:re.sub(r'\s', lambda m: '[' + m.group(0) + ']', text, 0);将字符串中的空格' '替换为'[ ]'。
(6) readlines
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
# # This library is created to search and replace related datas # Author: [email protected] # Created Date: 2015/02/13 # import os, re, time, fnmatch, difflib RE_TYPE = type(re.compile("")) class SearchAndReplace(object): def __init__(self, search_path, search_string, replace_string, search_only=True, file_filter=("*.*",)): self.search_path = search_path self.search_string = search_string self.replace_string = replace_string self.search_only = search_only self.file_filter = file_filter assert isinstance(self.file_filter, (list, tuple)) self.is_re = isinstance(self.search_string, RE_TYPE) print "Search '%s' in [%s]..." % ( self.search_string, self.search_path ) print "_" * 80 time_begin = time.time() file_count = self.walk() print "_" * 80 print "%s files searched in %0.2fsec." % ( file_count, (time.time() - time_begin) ) def walk(self): file_count = 0 for root, dirlist, filelist in os.walk(self.search_path): for filename in filelist: for file_filter in self.file_filter: if fnmatch.fnmatch(filename, file_filter): self.search_file(os.path.join(root, filename)) file_count += 1 return file_count def search_file(self, filepath): f = file(filepath, "r") old_content = f.read() f.close() if self.is_re or self.search_string in old_content: new_content = self.replace_content(old_content, filepath) if self.is_re and new_content == old_content: return print filepath def replace_content(self, old_content, filepath): if self.is_re: new_content = self.search_string.sub(self.replace_string, old_content) if new_content == old_content: return old_content else: new_content = old_content.replace( self.search_string, self.replace_string ) print "Write new content into %s\n" % filepath, return new_content if __name__ == "__main__": SearchAndReplace( search_path="C:\\Users\\xuan_qi\\Desktop\\12", # e.g.: simple string replace: search_string='the old string', replace_string='the new string', # e.g.: Regular expression replacing (used re.sub) #search_string = re.compile('{% url (.*?) %}'), #replace_string = "{% url '\g<1>' %}", search_only=True, file_filter=("*.py",), # fnmatch-Filter )
、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、、
import sys,os,os.path def file_replace(): path = "C:\\Users\\xuan_qi\\Desktop\\12\\new 2.txt" old_data = "new" for i in [1,2,3,4]: new_data = "new"+str(i) if not os.path.exists(path): print 'file of dir does not exists!\n' return elif os.path.isdir(path): for root,dirs,files in os.walk(path): for fn in files: filepath = os.path.join(root,fn) f = open(filepath,'r+') line = f.readlines() #f.seek(0) for s in line: f.write(s.replace(old_data,new_data)) f.close() elif os.path.isfile(path): f = open(path,'r+') line = f.readlines() #f.seek(0) for s in line: f.write(s.replace(old_data,new_data)) f.close() else: print 'illegal,not a file or dir\n' return if __name__=='__main__': file_replace()