python识别文件格式_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

。。。。。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值