python读取txt文件

应用场景: 测试过程中如果需要脚本进行数据读取. 

在 一个data.txt文件中,有如下格式的数据:

url:http://www.weather/api/city/signup,mobilephone:13060246701,pwd:123456

url:http://www.weather/api/city/signin,mobilephone:15678934552,pwd:234555

需要将其读取出来,并进行整理成下列格式:

[{'url': 'http://www.weather/api/city/signup', 'mobilephone': '13060246701', 'pwd': '123456'},

{'url': 'http://www.weather/api/city/signin', 'mobilephone': '15678934552', 'pwd': '234555'}]

 

def get_data_out(file_path):
    file = open(file_path, 'r', encoding="utf-8")
    lis = []
    for f in file:
        # print(f)
        dic = {}
        sb = f.strip().split(',')
        for s in sb:
            sub = s.split(':', 1)
            # print(sub)
            dic[sub[0]] = sub[1]
        # print(sb)
        lis.append(dic)
    file.close()
    return lis

if __name__ == '__main__':
    file_path = "data.txt"
    lis = get_data_out(file_path)
    print(lis)

 

用到的方法:

open() 打开文件 模式有 r, w 等

readlines()  读取数据. readline()读取一行

split()  切割,返回列表

strip()  去掉两端的空格和换行

 

posted @ 2019-08-15 15:29  lingxiasandu  阅读(733)  评论(0编辑  收藏  举报