文件操作
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}......] 并计算出总价钱。
lis0 = []
total_price = 0
with open('a', mode='r+', encoding='utf-8') as f:
for line in f:
dic = {}
lis = line.split()
dic['name'] = lis[0]
dic['price'] = lis[1]
dic['amount'] = lis[2]
lis0.append(dic)
total_price += int(lis[1]) * int(lis[2])
print(lis0)
print(total_price)
2,有如下文件:
-------
alex是老男孩python发起人,创建人。
alex其实是人妖。
谁说alex是sb?
你们真逗,alex再牛逼,也掩饰不住资深屌丝的气质。
----------
将文件中所有的alex都替换成大写的SB。
with open('alex', mode = 'r+', encoding = 'utf-8') as f: for line in f: if 'alex' in line: print(line.replace('alex', 'SB'))