# r : read 只讀 f = open("大猩猩.txt",mode = "r", encoding = "utf-8") # 讀取內容 f1 = f.read() # 所有都讀取出來 print(f) f2 = f.read() # 讀取不到內容,上邊已經讀取完畢,光標在末尾 print(f2) # 關閉鏈接 f.close()
f = open('夢想', mode = 'w', encoding = 'utf-8') f.write('好聲音\n') f.write('奇葩說\n') f.write('邏輯思惟') f1 = f.read() print(f1) # 報錯:not readable f.flush() f.close()
f = open('心門', mode = 'a', encoding = 'utf-8') f.write('好聲音\n') f.write('奇葩說\n') f.write('邏輯思惟') f.flush() f.close()
import os f1 = open('心門', mode='r', encoding='utf-8') f2 = open('心門_副本', mode='w', encoding='utf-8') for line in f1: if '好' in line: line = line.replace('好','真的很是好,及其好') f2.write(line) f1.close() f2.flush() f2.close() # time.sleep(3) # 刪除源文件 os.remove("心門") # 將新的文件重命名爲原來的文件 os.rename('心門_副本','心門')
import os with open('心門', mode='r',encoding='utf-8') as f1 ,\ open('心門_副本', mode='w',encoding='utf-8') as f2: for line in f1: if '好' in line: line = line.replace('好','真的很是好,及其好') f2.write(line) # time.sleep(3) os.remove('心門') os.rename('心門_副本','心門')
a1.txt 內容以下: name:apple price:10 amount:3 year:2012 name:tesla price:100000 amount:1 year:2013 name:mac price:3000 amount:2 year:2014 name:lenovo price:30000 amount:3 year:2015 name:chicken price:10 amount:3 year:2016 經過代碼,將其構建成這種數據類型: [{'name':'apple','price':10,'amount':3}, {'name':'tesla','price':1000000,'amount':1}......] 並計算出總價錢。 ''' with open('a2.txt', mode='r', encoding='utf-8') as f: lst = [] sum = 0 for line in f: line = line.strip().split(' ') dic = {} for c in line: c = c.split(':') if c[0] =='price' or c[0] =='amount': dic[c[0]] = int(c[1]) else: dic[c[0]] = c[1] sum += dic["price"] * dic["amount"] lst.append(dic) print(lst) print(sum)