2014-10-04 67 views
0

我的任務是製作這個程序。一個讀取tests.txt的程序會顯示所有分數以及分數的平均值。該程序還必須使用循環。在python中掙扎的項目

這是我到目前爲止有:

def main(): 

    scorefile = open('test.txt', 'r') 

    test1 = scorefile.readline() 
    test2 = scorefile.readline() 
    test3 = scorefile.readline() 
    test4 = scorefile.readline() 
    test5 = scorefile.readline() 

    scorefile.close() 

    print(test1, test2, test3, test4, test5) 

    total = (test1 + test2 + test3+ test4 + test5)/5.0 

    print('The average test score is:', total) 
main() 

我寫信給test.txt文件已經與這些數字:

95 
87 
79 
91 
86 
+2

歡迎的StackOverflow!請務必詢問實際問題,以便我們明確瞭解我們如何爲您提供幫助。 – 2014-10-04 02:57:43

+0

默認情況下,這些值以字符串形式存儲在本地變量中。你必須將它們轉換爲浮點數或整數才能工作。 – karthikr 2014-10-04 02:59:31

回答

5

所以假設你有這樣的文件:

95 
87 
79 
91 
86 

在任何語言中,我們需要:

  1. 打開文件;
  2. 通過循環遍歷文件中的所有行來讀取文件中的值,直到文件耗盡;
  3. 處理每個值(它們可能需要從字符串轉換爲int)
  4. 將所有讀取的值相加,然後除以讀取的值的數量。

在Python,那幾招被翻譯爲:

nums=list()      # we will hold all the values in a list       
with open(fn, 'r') as f:   # open the file and establish an iterator over the lines 
    for n in f:     # iterate over the lines 
     nums.append(int(n))  # read a line, convert to int, append to the list 

在互動提示,可以 '打印' NUMS:

>>> nums 
[95, 87, 79, 91, 86] 

現在你可以打印nums和平均數字:

print nums, sum(nums)/len(nums) 
[95, 87, 79, 91, 86] 87 

如果要打印nums不同,使用加入:

print '\n'.join(map(str, nums)) 

print '\t'.join(map(str, nums)) 

也許更習慣的方法把它寫在Python專門可能是:

with open(fn, 'r') as f: 
    nums=map(int, f) 
    print nums, sum(nums)/len(nums) 

有一個完全不同的討論中如果該文件可能太大而不適合計算機的內存。

對於大文件,你只需要保持一個運行總數和一個計數,而且你不需要把整個文件加載到內存中。在Python中,你可以這樣做:

with open(fn) as f: 
    num_sum=0 
    for i, s in enumerate(f, 1): 
     print s.strip() 
     num_sum+=int(s) 

    print '\n', num_sum/i 
0

我評論的代碼,這樣你就可以瞭解整個過程一步一步:

# first, let's open the file 
# we use with so that it automatically closes 
# after leaving its scope 
with open("test.txt", "r") as readHere: 
    # we read the file and split by \n, or new lines 
    content = readHere.read().split("\n") 
    # store scores here 
    scores = [] 
    # count is the number of scores we have encountered 
    count = 0 
    # total is the total of the scores we've encountered 
    total = 0 
    # now, loop through content, which is a list 
    for l in content: 
     count += 1   # increment the scores seen by one 
     total += int(l)  # and increase the total by the number on this line 
     scores.append(int(l)) # add to list 
    #one the loop has finished, print the result 
    print("average is " + str(total/count) + " for " + str(count) + " scores") 
    # print the actual scores: 
    for score in scores: 
     print(score) 
0

一般方法

def myAssignmentOnLOOPs(): 
    aScoreFILE = open("tests.txt", "r") 
    aSumREGISTER = 0 
    aLineCOUNTER = 0 
    for aLine in aScoreFILE.readlines(): # The Loop: 
     aLineCOUNTER += 1     #  count this line 
     aSumREGISTER += int(aLine)  #  sum adds this line, converted to a number 
     print aLine      #  print each line as task states so 
    # FINALLY: 
    aScoreFILE.close()      # .close() the file 
    if (aLineCOUNTER != 0):    # If() to avoid DIV!0 error 
     print "Finally, the Sum: ", aSumREGISTER 
     print "   an Avg: ", aSumREGISTER/aLineCOUNTER 
    else: 
     print "There were no rows present in file:tests.txt"