python 读取固定格式文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
环境:这几天在使用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
程序文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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.strip('\n'):
print "TITLE IS :", tit
for j in range(3):
print "content ", (j+1), "is: ", tit.strip('\n')
break
else:
print 'no this title'
exit(0)
这样,对于我的数据库配置信息就很好根据需要来进行获取了,只需要将title放进python程序就可以去处对应的数据库连接信息
user:root
password:123456
db_name:study
host:127.0.0.1
port:3306
charset:utf8
user:root
password:123456
db_name:wwwsite
host:127.0.0.1
port:3306
charset:utf8
。。。。。
页:
[1]