[英]Python dictreader KeyError issue
尝试从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']或其他任何内容。
谢谢! 马特
您正在写到databaseLocal
,但是试图从d
读取。 您确定他们引用的是同一个文件吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.