Reputation: 86
I am getting a keyerror when trying to read data from a csv. Below is the code that writes to the csv, followed by the code that reads from it. Python 2.7 on Ubuntu. Any help is appreciated!
#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()
When I just print 'row.keys()' all three of the keys show up. Not sure why I can't access 'row['pid'] or any of the others.
Thanks! Matt
Upvotes: 1
Views: 1089
Reputation: 41
You are writing to databaseLocal
, but trying to read from d
. Are you sure they are referencing the same file?
Upvotes: 1