class_07作业
#!/user/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020/6/1 0001 22:24 # @Author : lemon_小张 # @Email :981874735@qq.com # @File :class_07作业.py # TODO ''' 1、有以下数据来自于一个嵌套字典的列表(可自定义这个列表),格式如下: person_info = [{"name":"yuze", "age": 18, "gender": "男", "hobby": "假正经", "motto": "I am yours"} , .... 其他] 创建一个txt文本文件,来添加数据 a.第一行添加如下内容: name,age,gender,hobby,motto''' person_info = [{"name": "yuze", "age": 18, "gender": "男", "hobby": "假正经", "motto": "I am yours"}] re = [] with open("小张.txt","w",encoding="utf-8") as file: for i in person_info: for key in i.keys(): if key not in re: re.append(key) file.write(','.join(re)) '''b.从第二行开始,每行添加具体用户信息,例如: yuze,17,男,假正经, I am yours cainiao,18,女,看书,Lemon is best!''' # person_info = [{"name": "yuze", "age": 17, "gender": "男", "hobby": "假正经", "motto": "I am yours"}, \ # {"name": "cainiao", "age": 18, "gender": "女", "hobby": "看书", "motto": "Lemon is best!"}] # re =[] person_info = [{"name":"yuze", "age": "17", "gender": "男", "hobby": "假正经", "motto": "I am yours"} , {"name":"cainiao", "age": "18", "gender": "女", "hobby":"看书", "motto": "Lemon is best!"} ] re=[] with open("小张.txt","w",encoding="utf-8") as file_info: for iteam in person_info: for keys in iteam.keys(): if keys not in re: re.append(keys) file_info.write(".".join(re)+'\n') file_info.write(",".join(list(person_info[0].values()))+'\n') file_info.write(",".join(list(person_info[1].values()))) file_info.close() '''编写如下程序 有两行数据,存放在txt文件里面(手动建立文件,并添加如下数据): url:/futureloan/mvc/api/member/register,mobile:18866668888@pwd:123456 url:/futureloan/mvc/api/member/recharge,mobile:18866668888@amount:1000 请利用上课所学知识,把txt里面的两行内容,取出然后返回如下格式的数据:(可定义函数) [{'url':'/futureloan/mvc/api/member/register','mobile':'18866668888','pwd':'123456'}, \{'url':'/futureloan/mvc/api/member/recharge','mobile':'18866668888','amount':'1000'}]''' # with open("test_data.txt","w",encoding="utf-8") as file: # file.write("url:/futureloan/mvc/api/member/register,mobile:18866668888@pwd:123456 \ # url:/futureloan/mvc/api/member/recharge,mobile:18866668888@amount:1000") def read_data(file): with open("test_data.txt", "w", encoding="utf-8") as file: file.write("url:/futureloan/mvc/api/member/register,mobile:18866668888@pwd:123456 \ url:/futureloan/mvc/api/member/recharge,mobile:18866668888@amount:1000") file=open(file,"r+") li =[] for iteams in file.readlines(): dict={} for iteam in iteams.strip('\n').split(","): dict[iteam.split(":",1)[0]] = iteam.split(":",1)[1] li.append(dict) file.close() return li read_data("test_data.txt")