Python csv输入输出算法

时间:2017-07-06 06:38:02

标签: python-3.x

我正在构建一个不使用模块的算法。 我的算法是从111.txt计算每行的值,其中

2,2,2,2
4,4,0,4
2,3,3,3

到222.txt。所以我想要的结果是

Column, Sum, Mean, STD, Median, Mode, Min, Max
1,8,2,0,2,2,2,2
2,12,3,2,4,4,0,4
3,11,2.75,0.5,3,3,2,3

我的算法是

infile = open("111.txt", "r")
outfile = open("222.txt", "w")

outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")

for line in infile:                             
    infileline = line.rstrip().split(",")
    infileline.sort()
    while line != "":
        total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
        mean = total / 4
        std =  ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
        median = (float(infileline[1]) + float(infileline[2])) / 2
        mode = 2
        minimum = float(infileline[0])
        maximum = float(infileline[3])
        line = infile.readline()

outfile.write("1")
outfile.write(",")
outfile.write("%1.0f" % total)
outfile.write(",")
outfile.write("%1.0f" % mean)
outfile.write(",")
outfile.write("%1.0f" % std)
outfile.write(",")
outfile.write("%1.0f" % median)
outfile.write(",")
outfile.write("%1.0f" % mode)
outfile.write(",")
outfile.write("%1.0f" % minimum)
outfile.write(",")
outfile.write("%1.0f\n" % maximum)

infile.close()
outfile.close()

但问题是我的算法只读取111.txt上的第一行 因此,结果如下222.txt

Column,Sum,Mean,STD,Median,Mode,Min,Max
1,8,2,0,2,2,2,2

另外,我一直在思考,但我不知道如何编写列的算法和模式的算法。

1 个答案:

答案 0 :(得分:0)

  1. 您的结果文件打开了' w'模式(按最后一个值重写文件),只需使用' a' (追加)模式。
  2. 脚本只写循环的最后一个操作,你必须在循环中添加写块。
  3. 您不需要此行line = infile.readline()
  4. 此代码必须如下所示:

    infile = open("111.txt", "r")
    outfile = open("222.txt", "a")
    outfile.write("Column,Sum,Mean,STD,Median,Mode,Min,Max\n")
    column = 0
    
    for line in infile:
        if line:
            column += 1
            infileline = line.rstrip().split(",")
            infileline.sort()
            total = float(infileline[0]) + float(infileline[1]) + float(infileline[2]) + float(infileline[3])
            mean = total / 4
            std =  ((float(infileline[0])**2 + float(infileline[1])**2 + float(infileline[2])**2 + float(infileline[3])**2) / 4) - mean**2
            median = (float(infileline[1]) + float(infileline[2])) / 2
            mode = 2
            minimum = float(infileline[0])
            maximum = float(infileline[3])
    
            outfile.write(str(column)+',')
            outfile.write(','.join("%1.0f"%i for i in (total, mean, std, median,
                                                       mode, minimum, maximum)))
            outfile.write('\n')
    
    infile.close()
    outfile.close()