Python Forum
csv.reader vs csv.dictReader
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
csv.reader vs csv.dictReader
#1
I'm having a lot of difficulty understanding the difference between csv.reader and csv.dictReader. The Python docs didn't shed much light for me on this point...
Basically when would I elect to use csv.reader and where is csv.dictReader the better choice (I feel the answer must relate to fieldnames?

So my questions are :
1) what is the difference between the two methods?
2) my code reprints the fieldnames when I use csv.dictReader
3) rightnow my fieldnames are in my csv file...how do I attach them to print with csv methods
(for example with csv.dictWriter it is fieldnames=['id','a','b','c','d']; somefile = csv.DictWriter(someotherfile, fieldnames=fieldnames];somefile.writeheader() what is csv.reader/csv.dictReader alternative?

here is my csv:
Output:
id-a-b-c-d 1-foo-1-2-0 2-bar-10-20-0 3-moo-2-3-0
here is my code:
opened_file = open('foo0.csv')
print(opened_file.read())#this prints out fine

with open('foo0.csv') as openme:
#also, how do I implement fieldnames with csv.reader OR csv.dictReader (the docs show me how to do this with csv.dictWriter only)
	readme = csv.DictReader(openme, delimiter='-')#this refuses to work...it simply reprint my 'fieldnames'
	for x in readme:
		print(' '.join(x))
my output:
Output:
id-a-b-c-d 1-foo-1-2-0 2-bar-10-20-0 3-moo-2-3-0 id a b c d id a b c d id a b c d
Reply
#2
In simple terms csv.reader and csv.writer work with list/tuple, while csv.DictReader and csv.DictWriter work with dict.
csv.DictReader and csv.DictWriter take additional argument fieldnames that are used as dict keys.
scores.csv
Output:
id,name,score 1,John,10 2,Annie,25 3,Jane,15
import csv

with open('scores.csv') as f:
    rdr = csv.reader(f)
    for line in rdr:
        print(type(line))
        print(line)
        
print ('\n\nusing DictReader \n')

with open('scores.csv') as f:
    rdr = csv.DictReader(f)
    print 'fieldnames:', rdr.fieldnames
    for line in rdr:
        print(type(line))
        print(line)
output

Output:
<type 'list'> ['id', 'name', 'score'] <type 'list'> ['1', 'John', '10'] <type 'list'> ['2', 'Annie', '25'] <type 'list'> ['3', 'Jane', '15'] using DictReader fieldnames: ['id', 'name', 'score'] <type 'dict'> {'score': '10', 'id': '1', 'name': 'John'} <type 'dict'> {'score': '25', 'id': '2', 'name': 'Annie'} <type 'dict'> {'score': '15', 'id': '3', 'name': 'Jane'} >>>
Reply
#3
(Mar-19-2018, 06:52 AM)mepyyeti Wrote:
readme = csv.DictReader(openme, delimiter='-')#this refuses to work...it simply reprint my 'fieldnames'

So the line above won't work b/c I'm missing fieldnames statement...the python docs aren't quite clear on this.

Also for a bare knuckles inventory system which is be better dictReader/Writer or Reader/Writer. If those are your only options... I'm leaning toward the use of dictionaries only because I can use the 'column'/fieldnames names as keys...
Reply
#4
(Mar-19-2018, 09:55 PM)mepyyeti Wrote: So the line above won't work b/c I'm missing fieldnames statement...the python docs aren't quite clear on this.
This is not True. Both with respect to working and documentation being not clear. From the docs
Quote:The fieldnames parameter is a sequence. If fieldnames is omitted, the values in the first row of file f will be used as the fieldnames. Regardless of how the fieldnames are determined, the ordered dictionary preserves their original ordering.

As to which one is better - I would not put it this way (better/worse). It depends on the particular setup and your preferences. I tend to prefer DictReader/DictWriter. However if your data comes from a database it will be list of tuples, so writer could be handy. On other hand you can easily turn list/tuple into dict usizng dict(zip(keys, values)) given you have the fieldnames as list/tuple (keys) and values as list too.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  xml simple reader kucingkembar 2 1,052 Aug-19-2022, 08:51 PM
Last Post: kucingkembar
  Having strange results from an RFID HID card reader - I'm stuck orbisnz 1 1,477 Mar-28-2022, 08:20 AM
Last Post: Larz60+
  Thoughts on interfacing with a QR code reader that outputs keystrokes? wrybread 1 1,468 Oct-08-2021, 03:44 PM
Last Post: bowlofred
  NFC reader code help johnroberts2k 1 2,569 Jul-02-2021, 08:43 PM
Last Post: deanhystad
  csv.reader(): Limit the number of columns read in Windows Pedroski55 9 5,187 Jan-23-2021, 01:03 AM
Last Post: pjfarley3
  Closing Files - CSV Reader/Writer lummers 2 2,604 May-28-2020, 06:36 AM
Last Post: Knight18
  csv reader kgiles 3 5,338 Nov-05-2019, 09:04 AM
Last Post: perfringo
  g Null Byte using DictReader eshwinsukhdeve 13 7,519 May-15-2019, 08:50 AM
Last Post: buran
  G code reader luisfelipepc 2 3,678 Aug-13-2018, 02:56 AM
Last Post: ichabod801
  Python code for gcode reader and representation ralmeida 1 6,243 Jul-31-2018, 09:20 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020