我有代碼,你可以在其中讀取一個名為 ranks 的文件,你必須確保等級 - 大小為 15 或更小的單詞 - 卡的名稱Power - 小于 100 的整數 - 卡的功率Number - 小于 100 的整數 - 這些卡片的數量然后你應該將這些字段中的每一個存儲到它們自己的列表中。這是我到目前為止所擁有的。我不確定如何做剩下的事情。# Reading from a filenumFile = open("ranks.dat", "r")while True: text = numFile.readline() text = text.rstrip("\n") if text=="": break print (text, end = "\t")numFile.close()ranks 文件的示例可以是:Captain,40,2General,35,1Lieutenant,25,2Colonel,20,3Major,15,2Admiral,10,5Corporal,5,6Sergeant,4,4Private,1,10
1 回答

慕尼黑8549860
TA貢獻1818條經驗 獲得超11個贊
with open(file, "r") as f:
for line in f:
arr = line.split(",")
if len(arr[0]) > 15:
# length condition not met, write necessary code here
pass
elif int(arr[1]) > 100:
# power greater than 100, write necessary code here
pass
elif int(arr[2]) > 100:
# number greater than 100, write necessary code here
pass
始終使用with打開一個file文件,這樣您就不必擔心關閉文件。
while True:
...
if text=="":
break
這不是閱讀file. 更好地使用.readlines()or 上的循環file。
添加回答
舉報
0/150
提交
取消