python文件操作及数据类型操作练习
编写如下程序 # 有两行数据,存放在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’}]
实现如下:
def get_data():
# 先写入文件内容
with open('test.txt', 'w+', encoding='utf-8') as file:
file.writelines(['url:/futureloan/mvc/api/member/register@mobile:18866668888@pwd:123456\n',
'url:/futureloan/mvc/api/member/recharge@mobile:18866668888@amount:1000'])
# 读取内容
with open('test.txt', 'r+', encoding='utf-8') as fs:
list1 = fs.readlines()
"# print(list1)"
list2 = [] # 定义一个空列表 用于存放最后的数据
for i in range(0, len(list1)):
dict1 = { } # 定义一个空字典 用来存放字典格式的数据
""
# 去掉\n 再通过@分割 得到两个列表
['url:/futureloan/mvc/api/member/register', 'mobile:18866668888', 'pwd:123456']
['url:/futureloan/mvc/api/member/recharge', 'mobile:18866668888', 'amount:1000']
""
j = list1[i].strip('\n').split('@')
"print(j)"
for k in j:
""
得到 ['url', '/futureloan/mvc/api/member/recharge']
['mobile', '18866668888']
['amount', '1000']
""
m = k.split(':') # 通过:分割 得到key value值
"# print(m)"
dict1[m[0]] = m[1] # 将key value 组成键值对
list2.append(dict1)
print(list2)
get_data()
执行结果图如下: