1

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

1 Answer 1

1

You are writing to databaseLocal, but trying to read from d. Are you sure they are referencing the same file?

Sign up to request clarification or add additional context in comments.

6 Comments

Sorry, maybe I should have included the previous line, which is 'for d in dbList:' and that databaseLocal should be included in dbList. If I comment out the print row['pid'] and just leave print row.keys(), I can clearly see that the rows are there.
If I just say print row instead of print row['key'], it prints out this '{'cpu,pid,memory': '_,13330,1336811520'} '
It looks like the reader incorrectly parses the file. Try setting the fieldnames parameter when creating the DictReader: reader = csv.DictReader(csvfile, fieldnames=fieldnames, quotechar='|')
OK here's an interesting development! It does work to say 'print row['cpu,pid,memory']'. It then prints out all three values. Did I somehow make it all one big key?
Yes, looks like you did. As I said, the DictReader incorrectly parses the input, so you need to specify the fieldnames.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.