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)