平均CSV列

时间:2013-12-27 01:32:46

标签: python csv

我试图通过让函数读取文件然后吐出平均值来平均我的csv文件中的第4列。该程序现在的工作方式是每次运行时,您的答案都会附加到csv文件中。因此,要立即使用此代码,您必须运行几次,或者只需制作csv文件并预先填充数据。带有'#'的最后几行代码就是我现在正在处理的地方。

import csv
import datetime
# imports modules

now = datetime.datetime.now()
# define current time when file is executed

how = str(raw_input("How are you doing?"))
why = str(raw_input("Why do you feel that way?"))
scale_of_ten = int(raw_input("On a scale of 1-10. With 10 being happy and 1 being sad. How happy are you?"))
#creates variables for csv file

x = [now.strftime("%Y-%m-%d %H:%M"),how,why,scale_of_ten]
# creates list for variables to be written in

with open ('happy.csv','ab') as f:
    wtr = csv.writer(f)
    wtr.writerow(x)
    f.close()

col = 4

values = []

stats = open('happy.csv')

with open('happy.csv','r') as f: #
    for line in csv.readlines():# 
        elements = line.strip().split(',') #
        values.append(int(elements[col]))#

csum = sum(values) #
cavg = sum(values)/len(values) #
print ("Sum of column %d: %f" % (col,csum)) #
print ("avg of column %d: %f" % (col, cavg)) #

但是,我从顶部的第一个答案中跟随此example收到此错误:

  File "stacked.py", line 28, in <module>
    for line in csv.readline():#
AttributeError: 'module' object has no attribute 'readline'

提前感谢您的帮助。我很想跳进熊猫。

2 个答案:

答案 0 :(得分:2)

错误很明显:

AttributeError: 'module' object has no attribute 'readline'

csv是一个没有属性readline的模块。 您需要做的是从csv文件读取行,而不是从csv模块

在第28行,你需要for lines in f.readlines():(因为f是你在第27行给出的名字)。

答案 1 :(得分:1)

如果您想使用CSV模块。它没有readline功能。 Yun可以使用reader

spamreader = csv.reader('happy.csv', delimiter=',', quotechar='')
for line in spamreader:
    ...

或者

with open('happy.csv','r') as f:
    for line in f.read():
        ...