我的算法需要在Python中处理不同数量的csv输入/输出元素

时间:2017-07-09 21:41:46

标签: python-3.x

此算法只能在包含四个元素的列表中使用csv文件。

但是,如果csv文件有多于或少于4个元素,我不知道如何算法。我在很多方面尝试了它并查看了所有网页,但仍然没有答案。

infilename = input("Enter the location of your input file : ")
outfilename = input("Enter the location of your input file : ")

infile = open(infilename, "r")
outfile = open(outfilename, "w")

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()

1 个答案:

答案 0 :(得分:0)

将所有代码包含在try-except语句中的“if line”中。它会有所帮助。