Python Forum

Full Version: csv reader
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm very early on in python, but I'm trying to process a csv file with this code:
# importing csv module 
import csv 
  
# csv file name 
filename = "admitOrders.csv"
  
# initializing the titles and rows list 
fields = [] 
rows = [] 
  
# reading csv file 
print('\nKGG - First 5 rows are:\n')
with open(filename, 'r') as csvfile: 
    # creating a csv reader object 
    csvreader = csv.reader(csvfile) 
      
    # extracting field names through first row 
    fields = csvreader.next()
I'm getting this error:

Error:
Traceback (most recent call last): File "processCSV.py", line 18, in <module> fields = csvreader.next() AttributeError: '_csv.reader' object has no attribute 'next'
Any suggestions?

Thanks

K
fields = next(csvreader)
this would do, however I would prefer to use csv.DictReader instead of csv.reader
please visit this link. ALL ABOUT CSV IN PYTHON this all what you need from basic to advance:
While choosing between different options while reading data from text files I have found useful following those loose rules:

- if data in file is 'table with header' -> use csv.DictReader (maps automagically)
- if data in file is 'table without header' -> provide headers and use csv.DictReader
- if data in file is not structured and has quotes '"' and/or other ('weird') formatting -> use csv.reader (handles these automagically)
- if data on rows is not structured -> iterate over fileobject rows directly and do your own magic

... and then there is pandas :-).

No 'one obvious way' here. Use tools you comfortable with.