如何让python读取文件以确保它符合限制

我有代码,你可以在其中读取一个名为 ranks 的文件,你必须确保


等级 - 大小为 15 或更小的单词 - 卡的名称


Power - 小于 100 的整数 - 卡的功率


Number - 小于 100 的整数 - 这些卡片的数量


然后你应该将这些字段中的每一个存储到它们自己的列表中。这是我到目前为止所拥有的。我不确定如何做剩下的事情。


# Reading from a file

numFile = 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,2

General,35,1

Lieutenant,25,2

Colonel,20,3

Major,15,2

Admiral,10,5

Corporal,5,6

Sergeant,4,4

Private,1,10


心有法竹
浏览 132回答 1
1回答

慕尼黑8549860

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。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python