zoukankan      html  css  js  c++  java
  • 对文件操作,对数据做运算

     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')
    为什么要坚持,想一想当初!
  • 相关阅读:
    实验八 进程间通信
    实验七 信号
    实验六 进程基础
    实验五 shell脚本编程
    实验四 Linux系统C语言开发环境学习
    实验三 linux系统用户管理及VIM配置
    实验二 Linux系统简单文件操作命令
    实验一 linux系统与应用准备
    myatbis的一个好的封装
    php上传微信素材
  • 原文地址:https://www.cnblogs.com/JerryZao/p/8660738.html
Copyright © 2011-2022 走看看