[英]How to make python read a file to make sure it's fits the restrictions
我有代码,您可以在其中读取名为 rank 的文件,您必须确保
等级 - 大小 15 或更少的单词 - 卡的名称
功率——Integer小于100——卡的功率
Number - Integer 小于 100 - 这些卡的数量
然后你应该将这些字段中的每一个存储到他们自己的列表中。 这就是我到目前为止所拥有的。 我不确定如何做 rest。
# 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()
等级文件的示例可能是:
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
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
的好方法。 最好在file
上使用.readlines()
或循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.