0

I want to read data from a CSV file but my output says field values in the rows are "None". It doesn't recognize the values in my CSV file.

Any ideas ?

Here's the code I am using :

import arcpy
import csv
arcpy.env.workspace = "D:"
csvfile             = "D:/file.csv"
domains = []
rows = []

with open(csvfile, 'r') as csvfile:
     reader = csv.DictReader(csvfile)
     for row in reader:
     try:
        domains.append(row.get('domain'))
        rows.append(row)
    except KeyError:
       rows = [row]

domains = list(set(domains))
print("Identified %s unique domains" % len(domains))
print("Identified %s codes" % len(rows))


print("Creating codes:")
for row in rows:
    print("%s\t%s\t%s" % (row.get('domain'), row.get('code'), row.get('code_description')))
   

Here's a sample of my csv file, very basic and tab delimitated.enter image description here

And here's the result i am getting : enter image description here

Here's the print of the rows: enter image description here

3
  • Please fix the indentation. Also, you may want to transform domains into a set from the start instead of appending to a list. Commented Sep 29, 2020 at 7:52
  • some_dict.get('some_key') will never raise a KeyError, it will return None if it can't find it. try swapping it to domains.append(row['domain']). Commented Sep 29, 2020 at 7:56
  • syntax error... Commented Sep 29, 2020 at 8:46

1 Answer 1

1

Aside from the indentaiton issues, try the following modification:

import arcpy
import csv
arcpy.env.workspace = "D:"
csvfile             = "D:/file.csv"
domains = set()
rows = []

with open(csvfile, 'r') as csvfile:
    reader = csv.DictReader(csvfile, delimiter=';')
    for row in reader:
        try:
            domains.add(row['domain'])
            rows.append(row)
        except KeyError:
            print("Couldn't parse", row)

print("Identified %s unique domains" % len(domains))
print("Identified %s codes" % len(rows))


print("Creating codes:")
for row in rows:
    print("%s\t%s\t%s" % (row.get('domain'), row.get('code'), row.get('code_description')))
Sign up to request clarification or add additional context in comments.

10 Comments

Thank you but there is a syntax error somewhere in your code
@Mar python version?
it's a python27
Python 2.7 reached end of support by january 2020, you should definetely update to python 3. I edited it to remove the python 3.6 addition (we are in 3.8 stable right now), f-strings.
yes you are right i should update to python 3 eventually. hence your updates are not working, now my csv reactes as it's empty , no results at all !
|

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.