共計 1454 個字符,預計需要花費 4 分鐘才能閱讀完成。
python 怎么取固定格式文件,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
環境:這幾天在使用 python 開發程序的過程中,需要連接到 mysql 數據庫,而且涉及到不同的服務器和不同的數據庫,前期使用測試服來做測試,不想在 python 程序里頻繁去更改數據庫的配置信息,于是想到將全部的數據庫配置寫進一個 db.conf 文件里去讀取,也是基于安全性的考慮。于是寫了一個基于固定格式的文件讀取程序,案例如下。測試文件內容: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: 讀取一行文件內容
line = the_file.readline()
return line
def next_block(the_file):
:param the_file:
:return: 讀取指定格式的一段內容
title = next_line(the_file)
# cg = next_line(the_file)
content = []
for i in range(3): #3 為文件內容的行數
content.append(next_line(the_file))
return title, content
my_file = open_file(1.txt , r)
a = raw_input(enter you name: ) # 可以在函數中以變量來調用,這里僅做測試用
for i in range(3): #3 為格式內容的段數
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)
這樣,對于我的數據庫配置信息就很好根據需要來進行獲取了,只需要將 title 放進 python 程序就可以去處對應的數據庫連接信息
[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
看完上述內容,你們掌握 python 怎么取固定格式文件的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注丸趣 TV 行業資訊頻道,感謝各位的閱讀!
正文完