我在尝试从csv读取数据时遇到了错误。下面是写入csv的代码,后跟从中读取的代码。 Ubuntu上的Python 2.7。任何帮助表示赞赏!
#setting up the csv
with open(databaseLocal, 'wb') as csvfile:
fieldnames = ['cpu', 'pid', 'memory']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames,
quotechar='|', quoting=csv.QUOTE_MINIMAL)
writer.writeheader()
#Here is one spot where it's written to...
if data[:6] == 'active':
print 'mem info received'
memInfo = data[7:-1]
writer.writerow({'cpu': '_', 'pid': pidValue, 'memory': memInfo})
#and here is where it's read from, there is a KeyError for the line
#where we try to get row['pid]
with open(d, 'rb') as csvfile:
reader = csv.DictReader(csvfile, delimiter=' ', quotechar='|')
for row in reader:
print row['pid']
print row.keys()
当我打印'row.keys()'时,所有三个键都出现了。不知道为什么我无法访问'row ['pid']或任何其他人。
谢谢! 马特
答案 0 :(得分:0)
您正在写信databaseLocal
,但正在尝试阅读d
。你确定他们引用了同一个文件吗?