1 # average5.py 2 def main(): 3 fileName = input("What file are the numbers in?") 4 infile = open(fileName, 'r') 5 sum = 0 6 count = 0 7 for line in infile: 8 sum = sum + eval(line) 9 count = count + 1 10 print("\nThe average of the numbers is ",sum/count) 11 main() 12 13 14 #================= RESTART: C:/Users/home/Desktop/average.py ================= 15 #What file are the numbers in?C:\Users\home\Desktop\python4\num.txt 16 17 #The average of the numbers is 10.5
在运行代码时必须将文件的路径以及文件的名称,还有文件的后缀输入。