亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何讓python讀取文件以確保它符合限制

如何讓python讀取文件以確保它符合限制

心有法竹 2022-12-20 11:28:27
我有代碼,你可以在其中讀取一個名為 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。


查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 109 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號