1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数。
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
通过代码,将其构建成这种数据类型:[{'name':'apple','price':10,'amount':3},{'name':'tesla','price':1000000,'amount':1}......] 并计算出总价钱。
sum = 0
s1 = []
with open('D:\Desktop\Learning\python\ds.txt','r') as f_read:
datad = f_read.readlines()
for line in datad:
print(line)
s = {}
s2 = line.strip().split()
s.setdefault('name',s2[0])
s.setdefault('price',s2[1])
s.setdefault('amount',s2[2])
sum += int(s2[1])
s1.append(s)
print(s1)
print(sum)
2,有如下文件:
alex是老男孩python发起人,创建人。
import os
with open('D:\Desktop\Learning\python\db.txt','r+',encoding='utf-8') as f_read ,\
open('D:\Desktop\Learning\python\dsa.txt','w+',encoding='utf-8') as f_wite:
date = f_read.read()
date = date.replace('alex','')
f_wite.write(date)
f_wite.seek(0)
print(f_wite.read())
os.remove('db.txt')
os.replace('dsa.txt','db.txt')