在python中挣扎着一个项目

时间:2014-10-04 02:54:36

标签: python loops file-io

我的任务是制作这个节目。读取tests.txt的程序会显示所有分数以及分数的平均值。该程序还必须使用循环。

这是我到目前为止所做的:

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

3 个答案:

答案 0 :(得分:5)

假设你有这个文件:

95
87
79
91
86

在任何语言中,我们都需要:

  1. 打开文件;
  2. 通过循环文件中的所有行来读取文件中的值,直到文件耗尽为止;
  3. 处理每个值(例如,他们可能需要从字符串转换为int)
  4. 将读取的所有值相加,然后除以读取的值的数量。
  5. 在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
    

答案 1 :(得分: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)

答案 2 :(得分: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"