今天因爲給BeauBeau提供的抽獎號碼做SQL文件,一開始收到ZIP文件解開壓縮之後被嚇到了——29個CSV文件,每個文件保存了1000個獎券ID和號碼-_-!
照上次一樣,打開每個CSV文件做先做單獨的SQL文件,每個SQL中有1000條插入語句,隨後將29個文件的所有SQL語句都複製粘貼到同一個總的SQL文件中。
CSV文件中的結構是“ID,NUMBER”的結構,其中ID是7位數字,NUMBER是11位數字。這樣用正則式來進行捕捉的時候就比較方便了,在Eclipse的查找/替換功能中所使用的正則式就是“(/d{7}),(/d{11})”,進行替換的文本內容就是“INSERT INTO cards VALUES ('$1','$2',now());”。使用這種方法對29個CSV文件中的內容進行替換。
接下來,由於我覺得手動複製粘貼這29000條插入語句實在是太痛苦了,所以打算用Python來完成這項工作。這是我第一次自己動手寫Python代碼,感覺還挺順利的。
所有代碼如下:
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)
程序的功能很簡單,這也是我在Python的道路上邁出的第一步。
有時間的時候重寫這段代碼,加入正則替換功能。