複製粘貼功能的Python程式_python

來源:互聯網
上載者:User
今天因為給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檔案中的內容進行替換。



所有代碼如下:
複製代碼 代碼如下:

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) 
程式的功能很簡單,這也是我在Python的道路上邁出的第一步。

有時間的時候重寫這段代碼,加入正則替換功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.