Getting specific line and value with Python DictReader

后端 未结 4 859
终归单人心
终归单人心 2021-01-14 08:28

I have a csv file and am trying to get one specific value on, say, line 20, column 3.

But so far, all I managed is to display all values on column 3 (here c

4条回答
  •  难免孤独
    2021-01-14 08:53

    In short, convert the output of csv.DictReader to a list format and access the values with index.

    Note: The value returned when you access by index will be an object with keys corresponding to the column names in the CSV file


    Use Case:

    I had a similar need. I only wanted to read a subset of rows, say lines 10-15 from a total of 100 lines.

    A simple solution that worked was to convert it into list:

    # Observe that I am converting the output of DictReader into a list format
    lines = list(csv.DictReader(open('somefile.csv', 'r')))
    
    # Once I have the list of objects, I can simple access it with range
    for i in range(10, 15):
        line = lines[i]
        # If you want to read the value of a specific column
        print line['column_name']
    

    Hope this helps.

提交回复
热议问题