Python: How do I use DictReader twice?

后端 未结 3 956
清歌不尽
清歌不尽 2021-01-04 08:22

This feels like a very basic question, but I can\'t find any mention of it elsewhere. I\'m a beginning Python user.

When I read in data using DictReader, and then us

3条回答
  •  长发绾君心
    2021-01-04 08:57

    If you want to re-use the reader, you could seek the file back to 0. But, if the first row int the csv are headings, then that will be part of the output:

    >>> f = open( 'file.csv', 'rbU' )
    >>> reader = csv.DictReader( f )
    >>> reader.next()
    {'col1': '6', 'col2': '0.9', 'col3': '8'}
    >>> f.seek(0)
    >>> reader.next()
    {'col1': 'col1', 'col2': 'col2', 'col3': 'col3'}
    >>> f.close()
    

    DictReader uses the first row as the dictionary keys (if they are not otherwise supplied). Creating a new reader object is a lot simpler. You can also copy the data into a data structure like a list and loop over that.

提交回复
热议问题