Python 3.2 skip a line in csv.DictReader

22,590

Solution 1

You use next(reader) instead.

Source: csv.DictReader documentation

Solution 2

Since Python 2.6 you should use next(foo) instead of foo.next().

Solution 3

It was considered a mistake in python2 to have the method called next() instead of __next__()

next(obj) now calls obj.__next__() just like str, len etc. as it should.

You usually wouldn't call obj.__next__() directly just as you wouldn't call obj.__str__() directly if you wanted the string representation of an object.

Handy to know if you find yourself writing unusual iterators

Share:
22,590

Related videos on Youtube

paragbaxi
Author by

paragbaxi

#safeandhappyinternet

Updated on January 25, 2020

Comments

  • paragbaxi
    paragbaxi over 3 years

    How do I skip a line of records in a CSV when using a DictReader?

    Code:

    import csv
    reader = csv.DictReader(open('test2.csv'))
    # Skip first line
    reader.next()
    for row in reader:
        print(row)
    

    Error:

    Traceback (most recent call last):
      File "learn.py", line 3, in <module>
        reader.next()
    AttributeError: 'DictReader' object has no attribute 'next'
    
    • John Machin
      John Machin over 12 years
      nothing to do with this problem, but you should be opening your file like this: open('test2.csv', newline='') ... see the csv.reader docs
    • paragbaxi
      paragbaxi over 12 years
      I read the CSV.Reader doc. This attribute appears to help preserve multiline CSVs. Since my CSV file is multiline, would it still be prudent to add newline='' to my open command?
  • Seth Johnson
    Seth Johnson over 12 years
    This is because it's Python 3, not Python 2.
  • tarikki
    tarikki over 6 years
    Thanks for the context!