2014-10-04 65 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"