008、py43-day09-sky-20210812

 

 

题目一:把以下字典分行添加到文件当中:
person_info = [
{
"name": "明鹏程",
"age": 22,
"gender": "男",
"hobby": "学习",
"motto": "学习使我快乐"
},
{
"name": "萌笑天",
"age": 20,
"gender": "女",
"hobby": "拿30K offer",
"motto": "下次拿个40K 的"
},
]

得到一个 info.txt 的文件:
name,age,gender,hobby,motto
明鹏程,22,男,学习, 学习使我快乐
萌笑天,20,女,拿30K offer,下次拿个40K 的

 

代码如下:

person_info = [
    {
        "name": "明鹏程",
        "age": 22,
        "gender": "",
        "hobby": "学习",
        "motto": "学习使我快乐"
    },
    {
        "name": "萌笑天",
        "age": 20,
        "gender": "",
        "hobby": "拿30K offer",
        "motto": "下次拿个40K 的"
    }
]


with open('info.txt', mode='a', encoding='utf-8') as file:
    result = []
    title = []
    for i in range(len(person_info)):
        if i == 0:
            data = []
            for k, v in person_info[0].items():
                title.append(f'{k}')
                data.append(f'{v}')
            title_name_str = ','.join(title)
            data_str = ','.join(data)

            result.append(title_name_str)
            result.append(data_str)
        if i > 0:
            data = []
            for v in person_info[i].values():
                data.append(f'{v}')
            data_str = ','.join(data)
            result.append(data_str)

    file.write('\n'.join(result))
View Code

执行结果如下,在同级目录下生成  info.txt  文件

name,age,gender,hobby,motto
明鹏程,22,男,学习,学习使我快乐
萌笑天,20,女,拿30K offer,下次拿个40K 的
View Code

 

 

题目二:手工准备cases.txt 文件,文件中手工复制 2 行数据:
url:/futureloan/mvc/api/member/register@mobile:18866668888@pwd:123456
url:/futureloan/mvc/api/member/recharge@mobile:18866668888@pwd:1000
请利用上课所学知识,把txt里面的两行内容取出然后保存到一个列表和字典当中:(可定义函数)
列表当中,有2个字典
每一行的数据,就是一个字典。
字典的key分别是:url,mobile,pwd

 

代码如下:

with open('cases.txt', mode='r', encoding='utf-8') as file:
    all_data = file.readlines()
    result_list = []
    temp = []
    # print(all_data)
    for data in all_data:
        data_list = data.strip('\n').split('@')
        # print(data_list)
        for key_value in data_list:
            # print(key_value)
            temp.append(key_value.split(':'))
        result_list.append(dict(temp))
    print(result_list)
View Code

执行结果如下:

[{'url': '/futureloan/mvc/api/member/register', 'mobile': '18866668888', 'pwd': '123456'},
{'url': '/futureloan/mvc/api/member/recharge', 'mobile': '18866668888', 'pwd': '1000'}] Process finished with exit code 0

 

posted @ 2021-08-12 22:41  空-山-新-雨  阅读(255)  评论(0编辑  收藏  举报