python中从文件中读取数据

 

 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

 

在运行代码时必须将文件的路径以及文件的名称,还有文件的后缀输入。

posted @ 2017-02-10 15:58  青海大学软件工程  阅读(1091)  评论(0)    收藏  举报