# 1、有以下数据来自于一个嵌套字典的列表(可自定义这个列表),格式如下:
# person_info = [{"name":"yuze", "age": 18, "gender": "男", "hobby": "假正经", "motto": "I am yours"} , .... 其他]
# 创建一个txt文本文件,来添加数据
# a.第一行添加如下内容:
# name,age,gender,hobby,motto
# b.从第二行开始,每行添加具体用户信息,例如:
# yuze,17,男,假正经, I am yours
# cainiao,18,女,看书,Lemon is best!
"""
思路:
一行一行存储
字符串:yuze,17,男,假正经, I am yours
列表当中,每一个字典的values.
list(字典.values())
用逗号将每一个value拼成一个字符串。
",".join(列表/元组) --- 每一个成员要是字符串
再写入文件当中。
函数 :封装成函数。
一部分:写文件。
二部分:就是从列表当中,得到一个字符串。
yuze,17,男,假正经, I am yours\n
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!"},
]
def get_value_lines(info):
"""获取每一行的数据
列表转化成行的字符串形式
[{}, {}] ==> name, yuz,
"""
lines = ''
for person in info:
line = []
# ['yuze', 17, '男']
for e in person.values():
line.append(str(e))
# 列表转化成字符串
line_str = ','.join(line) + '\n'
lines += line_str
return lines
def main():
"""主体逻辑"""
# os.path
# ['name', 'age',]
#
# title = person_info[0].keys()
with open('info.txt', 'w+') as f:
f.write('name,age,gender,hobby,motto\n') # byte
data = get_value_lines(person_info)
with open('info.txt', 'a', encoding='utf-8') as f:
f.write(data)
# with open('info.txt', 'r', encoding='utf-8') as f:
# print(f.read())
main()
# 编写如下程序
# 有两行数据,存放在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("work.txt","r",encoding="utf-8") as fs:
# a = fs.readlines()
# list1 = []
# dict2 = {}
# for i in a:
# j = i.rstrip().split("@")
# for k in j:
# m = k.split(":")
# # print(m)
# dict2[m[0]] = m[1]
# list1.append(dict2)
# print(list1)