python中从文件中读取数据2

#average7.py 文件中有多行,且每行有多个数字用逗号隔开
def main():
    fileName = input("What file are numbers in?")
    infile = open(fileName,'r')
    sum = 0.0
    count = 0
    line = infile.readline()
    while line != "":
    #为line中的值更新其count和sum
        for xStr in line.split(","):
            sum = sum + eval(xStr)
            count = count + 1
        line = infile.readline()
    print("\nThe average of the numbers is ",sum/count)

main()

文件读取中的一些函数

read()            返回值为包含整个文件内容的一个字符串

readline()       返回值为文件下一行内容的字符串

readlines()     返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串

原文地址:https://www.cnblogs.com/pingliu/p/6386903.html