我必須創建一個固定大小的陣列,然后從資料檔案中部分填充。固定大小需要為 10,檔案中有 3 行。使用我當前的代碼,我在陣列中得到七個列為 ' ' 的專案如何編輯此代碼以僅部分填充陣列并忽略空位?
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()
uj5u.com熱心網友回復:
正如@LarrytheLlama 評論的那樣,嘗試使用 append:
# you do not need str() because rstrip() return str.
colors.append(rstrip(line))
如果您不將其用于其他目的,您也可能希望洗掉“計數器”。
uj5u.com熱心網友回復:
問題出在以下行中:
colors[counter] = str.rstrip(line)
應該:
colors[counter] = line.rstrip()
說明:您的變數line是一個型別為 的物件str,并且rstrip是一個 的方法str。呼叫line.rstrip()回傳一個 rstripped 副本line。
編輯:根據您的評論,我現在了解您正在尋找什么結果。您只想從檔案中讀取最多 10 行或更少的行,并將值(不帶換行符)放入串列中。
我冒昧地重寫了您的程式,不僅是為了解決您遇到的問題,而且還對其進行了清理和簡化。我希望這段代碼向您展示了一些對您有用的其他技巧。
MAX_COLORS = 10
colors = []
filename = input("Enter the name of the color file (primary.dat or secondary.dat): ")
infile = open(filename, 'r')
while len(colors) < MAX_COLORS:
line = infile.readline()
if not line:
break
colors.append(line.rstrip())
infile.close()
print('The colors are:')
for color in colors:
print(' %s' % color)
這樣做的問題是,如果您在檔案末尾有一個額外的換行符(這很容易意外發生),否則該空行將作為顏色讀入。你可能不想那樣。為了解決這個問題,你可以這樣做:
line = infile.readline().rstrip()
if not line:
break
colors.append(line)
這將導致您的程式在第一個空行或檔案末尾停止讀取,以先到者為準。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/355605.html
上一篇:字計數器回傳錯誤的字數
