python学习之老男孩python全栈第九期_day008作业
1. 文件a.txt内容:每一行内容分别为商品名字,价钱,个数,求出本次购物花费的总钱数
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
1 sum = 0 2 with open('a.txt',mode='w',encoding='utf-8') as f: 3 f.write('''apple 10 3 4 tasla 100000 1 5 mac 3000 2 6 lenove 30000 3 7 chicken 10 3''') 8 with open('a.txt',encoding='utf-8') as read_f: 9 for line in read_f.readlines(): 10 sum += int(line.split(' ')[1])*int(line.split(' ')[2]) 11 print(sum)
2. 修改文件内容,把文件中的alex都替换成SB
1 import os 2 with open('a.txt',mode='w',encoding='utf-8') as f: 3 f.write('''alex 18 4 Eva 20 5 KID 21 6 kidd 22 7 alex 38''') 8 with open('a.txt',encoding='utf-8') as read_f,\ 9 open('aa.txt',mode='w',encoding='utf-8') as write_f: 10 for line in read_f.readlines(): 11 line = line.replace('alex','SB') 12 write_f.write(line) 13 os.remove('a.txt') 14 os.rename('aa.txt','a.txt')