您好,登錄后才能下訂單哦!
python怎么取固定格式文件,相信很多沒有經(jīng)驗(yàn)的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個(gè)問題。
環(huán)境:這幾天在使用python開發(fā)程序的過程中,需要連接到mysql數(shù)據(jù)庫,而且涉及到不同的服務(wù)器和不同的數(shù)據(jù)庫,前期使用測試服來做測試,不想在python程序里頻繁去更改數(shù)據(jù)庫的配置信息,于是想到將全部的數(shù)據(jù)庫配置寫進(jìn)一個(gè)db.conf文件里去讀取,也是基于安全性的考慮。 于是寫了一個(gè)基于固定格式的文件讀取程序,案例如下。 測試文件內(nèi)容: title1 1,line 1 2,line 2 3,line 3 title2 4,line 4 5,line 5 6,line 6 title3 7,line 7 8,line 8 9,line 9
程序文件:
def open_file(filename, mode='r'): """ :param filename: :param mode: :return: 返回文件句柄 """ try: the_file = open(filename, mode) except IOError: print "Unable to open the file", filename sys.exit(0) else: return the_file def next_line(the_file): """ :param the_file: :return: 讀取一行文件內(nèi)容 """ line = the_file.readline() return line def next_block(the_file): """ :param the_file: :return: 讀取指定格式的一段內(nèi)容 """ title = next_line(the_file) # cg = next_line(the_file) content = [] for i in range(3): #3為文件內(nèi)容的行數(shù) content.append(next_line(the_file)) return title, content my_file = open_file('1.txt', 'r') a = raw_input("enter you name: ") #可以在函數(shù)中以變量來調(diào)用,這里僅做測試用 for i in range(3): #3為格式內(nèi)容的段數(shù) tit = next_block(my_file) if a == tit[0].strip('\n'): print "TITLE IS :", tit[0] for j in range(3): print "content ", (j+1), "is: ", tit[1][j].strip('\n') break else: print 'no this title' exit(0)
這樣,對于我的數(shù)據(jù)庫配置信息就很好根據(jù)需要來進(jìn)行獲取了,只需要將title放進(jìn)python程序就可以去處對應(yīng)的數(shù)據(jù)庫連接信息
[test]
user:root
password:123456
db_name:study
host:127.0.0.1
port:3306
charset:utf8
[mysql]
user:root
password:123456
db_name:wwwsite
host:127.0.0.1
port:3306
charset:utf8
看完上述內(nèi)容,你們掌握python怎么取固定格式文件的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。