文件操作
1.将文件内容中含有保罗的,替换为哈登
1 import os 2 #第1步 3 with open('log',encoding='utf-8') as f1,\ 4 open('log.bak',encoding='utf-8',mode='w') as f2: 5 for i in f1: 6 #第3步 7 new_i = i.replace('保罗', '哈登') 8 #第4步 9 f2.write(new_i) 10 #第4步 11 os.remove('log') 12 #第5步 13 os.rename('log.bak','log')
2.文件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
}......] 并计算出总价钱。
1 li = [] 2 the_sum = 0 3 name_list = ['name','price','amount','year'] 4 with open('a.txt',encoding='utf-8') as f1: 5 for i in f1: 6 l2 = i.strip().split() 7 dic = {} 8 for j in range(len(l2)): 9 dic[name_list[j]] = l2[j] 10 li.append(dic) 11 #遍历列表 12 for i in li: 13 #计算总价格(单价*个数) 14 the_sum += int(i['price']) * int(i['amount']) 15 16 print(li) 17 print('总价钱为: {}'.format(the_sum))