I have to create an array with a fixed size and then fill partially from a data file. The fixed size needs to be 10 and there are three lines in the file. With my current code i get seven items in the array listed as ' ' how do I edit this code to just partially fill the array and ignore the empty spots?
MAX_COLORS = 10
colors = [''] * MAX_COLORS
counter = int(0)
filename = input("Enter the name of the color file (primary.dat or secondary.dat): ")
infile = open(filename, 'r')
line = infile.readline()
while line != '' and counter < MAX_COLORS:
colors[counter] = str.rstrip(line)
counter = counter 1
line = infile.readline()
infile.close()
CodePudding user response:
The problem is in the following line:
colors[counter] = str.rstrip(line)
Should be:
colors[counter] = line.rstrip()
Explanation: Your variable line
is an object of type str
, and rstrip
is a method of str
. Calling line.rstrip()
returns an rstripped copy of line
.
CodePudding user response:
As @ LarrytheLlama comments, try to use append:
# you do not need str() because rstrip() return str.
colors.append(rstrip(line))
Also you might want to remove 'counter' if you do not use it for other purpose.