统计文件内数据 Python

python 是一门很简单的脚本语言, 不过很久没用了, 好多东西都忘得差不多了。正好昨天晚上,老板让测试相机的拍图时间, 于是我们连续抓取了200幅图像, 并他们的拍图时间间隔写入到了txt文件中。
使用C++一个while循环可以很容易的解决这个问题, 不过突然间想装逼, 练习下python的使用。
程序很简单, 就是要实现对文件内每行数据的读取, 计算他们的均值。
涉及python类的书写, 文件操作的一些内容, 好久不写还是遇到一些麻烦的, 这里做一些记录。
源代码如下:

#coding:utf-8

'''
Created on 2016-3-21
@attention: this file is used to compute the average of the data in the text file
@author: ThinkPad User
'''

import os

class Files:
    # 记录文件路径
    __path = ''

    # 设置文件路径
    def __init__(self, path):
        self.__path = path

    # 载入文件数据, 并计算他们的平均值
    def loadData(self):
        if os.path.isfile(self.__path):
            fp = open(self.__path, "r")
            sum = 0
            total_num = 0
            while True:
                data = fp.readline()
                if data:
                    total_num += 1
                    sum += int(data)
                else:
                    break
            fp.close()     
            aver = sum / total_num
            print aver       


if __name__ == '__main__':
    path = "E:\\system dir\\desktop\\test_save_tiff.txt"
    f = Files(path)
    f.loadData()

参考资料
1.怎么解决python “Non-ASCII character”错误
简单来说, 就是在开始位置设置utf-8编码格式: #coding:utf-8
2.TypeError: unbound method loadData() must be called with Files instance as first argument (got nothing instead)
后来研究发现, python的类也需要初始化, 当没有输入参数的时候, 括号还是不能省略的, 这里就是将 Files() 写成 Files 的后果
3.Python int与string之间的转化
简单来讲, 我们使用readline 读入的数据都是string类型的, 需要转化为int类型才能进行数据统计
4.python类的定义
5.python的文件操作
6.用python读取文本文件,对读出的每一行进行操作,这个怎么写?

你可能感兴趣的:(python,python)