- 了解 Python 如何更新 CSV 檔案內容!
處理過程實作
- 先準備好需要更新的 CSV 檔案, stores.csv
ID,name,owner,prize 1,日本,-1,2500 7,加拿大,-1,3500 13,英國,-1,4500 19,埃及,-1,1200 2,南韓,-1,2000 8,美國,-1,4300 14,法國,-1,4200 20,象牙海岸,-1,2200 4,台灣,-1,2500 10,巴拿馬,-1,3500 16,德國,-1,3800 22,南非,-1,1800 5,新加坡,-1,3000 11,阿根廷,-1,2800 17,立陶宛,-1,1700 23,印度,-1,1800
- 撰寫一個 Stores.py 的類別程式,可讀取 stores.csv 檔案:
import csv class Stores: def __init__(self): self.__id = [] self.__name = [] self.__owner = [] self.__prize = [] with open('stores.csv', newline='',encoding='utf-8') as csvfile: rows = csv.DictReader(csvfile) for row in rows: self.__id.append(row['ID']) self.__name.append(row['name']) self.__owner.append(row['owner']) self.__prize.append(row['prize']) def getStoreData(self,po): index = self.__id.index(po) print(self.__name[index]) if __name__ == "__main__": myStore = Stores() myStore.getStoreData(str(2))
- 修改 Stores.py ,將更新後的資料,可以寫入原讀取的資料行:
(前方略過....) def setStoreData(self,newdata): index = self.__id.index(newdata[0]) self.__owner[index] = newdata[2] with open('stores.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile) length = len(self.__id) writer.writerow(['ID','name','owner','prize']) for i in range(0,length): writer.writerow([self.__id[i],self.__name[i],self.__owner[i],self.__prize[i]]) if __name__ == "__main__": myStore = Stores() result = myStore.getStoreData(str(2)) result[2] = '1' myStore.setStoreData(result) newresult = myStore.getStoreData(str(2)) print(newresult)
- 加入 Stores 類別,修改遊戲主要流程:
# 加入 Stores 類別 import Stores (中間一堆程式碼,略過!) ##### c.) 移動到骰子點數的框格 newpo = players[i].getPo() # I. 可能經過起點 if newpo >= areas: newpo = playerPo(newpo) if newpo == 0: print("玩家回到「開始」位置:", newpo) elif newpo < (areas/4): print("玩家越過「開始」位置:", newpo) print("玩家在新位置:",newpo) # II. 可能落在邊角框格 if (newpo == 6): print("玩家休息一天") elif (newpo == 18): print("玩家再玩一次") # III. 可能是在機會與命運框格 ## 機會的地圖編號是 3,15 兩個號碼 elif ((newpo == 3) or (newpo == 15)): myChance = Chance.Chance() chances = myChance.choice() print("玩家中機會:",chances[0]) # IV. 可能是在地產框格 else: playerStore = Stores.Stores() store = playerStore.getStoreData(str(newpo)) ## 判斷是否有人己取得該地產所有權了 if store[2] == '-1': print("該地產無人所有!") else: print("該地產為:" + str(players[store[2]].getName()) + "所有") (剩下的程式碼略過....)