python怎么取固定格式文件

发布时间:2021-10-27 17:14:30 作者:柒染
来源:亿速云 阅读:234

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怎么取固定格式文件的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

推荐阅读:
  1. python如何爬取图片
  2. python如何爬取ajax

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:Python中的if语句怎么用

下一篇:Mysql数据分组排名实现的示例分析

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》