1. 程式人生 > >檔案操作課後練習

檔案操作課後練習

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}......] 並計算出總價錢。

# 第1題
#-*- coding:utf-8 -*-
# author: jujiqing
# QQ: 354100640
# blog:https://www.cnblogs.com/niumao/
# datetime:2019/1/5 list = [] with open('love', 'r', encoding='utf-8')as f: for n in f: list2 = n.strip().split() dic = {'name': list2[0], 'price': list2[1], 'amount': list2[2]} list.append(dic) print(list) sum = 0 for dic in list: sum = sum +int(dic['price']) * int(dic['
amount']) print(sum)

 

 

 

2,有如下檔案:

-------

alex是老男孩python發起人,建立人。

alex其實是人妖。

誰說alex是sb?

你們真逗,alex再牛逼,也掩飾不住資深屌絲的氣質。

----------

將檔案中所有的alex都替換成大寫的SB。

# 第2題
#-*- coding:utf-8 -*-
# author: jujiqing
# QQ: 354100640
# blog:https://www.cnblogs.com/niumao/
# datetime:2019/1/5 

with open('love', mode='r+',encoding='utf-8') as f,open('love.bak', mode='w',encoding='utf-8') as f2:
    f1 = f.read()
    f1 = f1.replace('alex','SB')
    f2.write(f1)
import os
os.remove('love')
os.rename('love.bak','love')