I have the code where you read a file called ranks and you have to make sure that the
Rank - Word of Size 15 or less - the Name of the Card
Power - Integer less than 100 - the Power of the Card
Number - Integer less than 100 - the Number of these cards
and then you're supposed to store each of those fields into their own lists. This is what I have so far. I'm not sure how to do the 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()
An example of a ranks file could be:
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
Always use with
to open a file
so that you don't have to worry about closing the file.
while True:
...
if text=="":
break
This is not a good way to read a file
. Better use .readlines()
or a loop on the file
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.