python怎么取固定格式文件-创新互联
python怎么取固定格式文件,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
程序文件:
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怎么取固定格式文件的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注创新互联行业资讯频道,感谢各位的阅读!
另外有需要云服务器可以了解下创新互联cdcxhl.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
当前名称:python怎么取固定格式文件-创新互联
文章链接:http://tyjierui.cn/article/cojdjo.html