2017-04-18 41 views
0

我將盡力解釋這一點。我是一個初學者(所以,請不要困難的術語lol)致力於一個圖書館用戶借書的代碼。每個用戶都有一個庫代碼和一些要使用的積分。這些細節在一個文本文件中。第一列是圖書館編號。第二欄是他們的貸方餘額。第三欄是最低信用額度。第四列是最大貸方餘額:如何讓我的代碼讀取文本文件的所有行?

ABC, 125, 150, 200 
ABD, 80, 30, 80 
ABE, 0, 23, 50 
ABF, 20, 20, 50 
ABG, 78, 30, 80 
ABH, 92, 90, 300 
ABI, 3, 9, 20 
ABJ, 7, 6, 38 

當餘額達到最小余額時,需要增加更多的餘額。我希望我的計劃能夠閱讀文本文件,並確定哪些用戶需要在其帳戶中添加更多信用額度才能超過最低信用餘額。我還想指定他們需要多少信用才能達到最大的貸方餘額。我希望將這些細節寫入單獨的文件中。這是我迄今爲止所做的:

f = open("customerInfo.txt", "r") 
for line in f.readlines(): 
z = line.split(", ") 
UserID = z[0] 
CreditBalance = z[1] 
MinBalance = z[2] 
MaxBalance = z[3] 
HowManyAwayFromMaxBalance = MaxBalance - CreditBalance 

if int(z[2]) - int(z[1] <= 0: 
    CreditInfo = open("creditinfo.txt", "w") #This is a blank text file 
    CreditInfo.write("User", UserID, "needs more credits. In order to reach the maximum credit balance, they would need", HowManyAwayFromMaxBalance, "credits added to their account./n" 

這不適用於每一行。我將如何編輯此代碼,以便它讀取每一行,併爲每行自己做同樣的事情?因爲數百個名字將被添加到這個列表中,所以我希望它自動發生。因此,在這種情況下,將自動在creditinfo.txt文件中打印用於爲賬戶ABC,ABE,ABF和ABI添加貸項的詳細信息。預先感謝您,請問這是否令人困惑。

+0

你能解決這個缺口,所以我們可以看到如何'for'循環的作品? – tdelaney

回答

1

您發佈的代碼中有幾處錯誤,我不清楚您的問題究竟是什麼。如果你可以解釋,請讓我知道。

這對我來說工作得很好:

f = open("customerInfo.txt", "r") 
fw = open("creditInfo.txt", "w") 

for line in f.readlines(): 
     z = line.split(", ") 
     UserID = z[0] 
     CreditBalance = int(z[1]) 
     MinBalance = int(z[2]) 
     MaxBalance = int(z[3]) 
     HowManyAwayFromMaxBalance = MaxBalance - CreditBalance 

     if (MinBalance - CreditBalance) <= 0: 
      fw.write("User " + UserID + " needs more credits. In order to reach the maximum credit balance, they would need " + str(HowManyAwayFromMaxBalance) + " credits added to their account.\n") 

f.close() 
fw.close() 
相關問題