CSV文件中的结构是“ID,NUMBER”的结构,其中ID是7位数字,NUMBER是11位数字。这样用正则式来进行捕捉的时候就比较方便了,在Eclipse的查找/替换功能中所使用的正则式就是“(/d{7}),(/d{11})”,进行替换的文本内容就是“INSERT INTO cards VALUES ('$1','$2',now());”。使用这种方法对29个CSV文件中的内容进行替换。
import sys, os def readFile(filename): file=open(filename, "r") s=file.read().strip() file.close() return s
def writeFile(filename, files): content=[] for f in files: print "reading file ' %s ' " % f s=readFile(f) print "read file ' %s ' completed" % f content.append(s) print "writing file ' %s ' " % filename file=open(filename, "w") file.write("/n/*-----This is a seperating line.-----*//n".join(content)) file.close() print "write file ' %s ' completed" % filename
filters=['.txt'] fullpath=os.getcwd();
print "opening directory: ' %s ' " % fullpath
sys.path.append(fullpath) files = os.listdir(fullpath) files =[f for f in files if os.path.splitext(f)[1].lower() in filters] writeFile("beaunet_be_card.sql", files)