对文件操作,对数据做运算
1 ''' 2 1. 文件test.txt内容:每一行内容分别为商品名字,价钱,个数,求出本次购物花费的总钱数 3 使用列表解析,从文件a.txt中取出每一行,做成下述格式:[{‘name’:'apple','price':10,'count':3},{...},{...},...] 4 apple 10 3 5 tesla 100000 1 6 mac 3000 2 7 lenovo 30000 3 8 chicken 10 3 9 10 11 ''' 12 # f = open('test.txt','r',encoding='utf-8') 13 # set = [] 14 # l = f.readline().split() 15 # print(l) 16 # set.append({'name':l[0],'price':l[1],'count':l[2]}) 17 # print(set) 18 19 # 1、 20 goods_info=[] 21 with open('test.txt','r') as f: 22 for line in f: 23 l = line.split() 24 goods_info.append({'name':l[0],'price':int(l[1]),'count':int(l[2])}) 25 ll = list(map(lambda x:x['price']*x['count'],goods_info)) 26 ss = sum(ll) 27 print(ll) 28 print(ss) 29 print(goods_info) # [{'name': 'apple', 'price': 10, 'count': 3}, {'name': 'tesla', 'price': 100000, 'count': 1}, {'name': 'mac', 'price': 3000, 'count': 2}, {'name': 'chicken', 'price': 200, 'count': 3}] 30 31 ''' 32 2. 修改文件内容,把文件中的alex都替换成SB 33 ''' 34 # 2、 35 import os 36 37 with open('a.txt','r',encoding='utf-8') as read_f, open('.a.txt.swap','w',encoding='utf-8') as write_f: 38 for line in read_f: 39 line = line.replace('alex','SB') 40 write_f.write(line) 41 42 os.remove('a.txt') 43 os.rename('.a.txt.swap','a.txt')
为什么要坚持,想一想当初!