Getting specific line and value with Python DictReader

后端 未结 4 822
终归单人心
终归单人心 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:42

    if you only know the column number and the line number you can do like this:

    TheRow = 2      # Note that row 1 is the header row
    TheColumn = 2   # first column == 0
    for row in d:
        if d.line_num == TheRow:
            print("row %s: %s" % (str(d.line_num), str(row) ) )
            print( row[d.fieldnames[TheColumn]] )
    

    output:

    row 2: {'t1': '12', 't2': '23', 't3': '31'}
    31
    
    0 讨论(0)
  • 2021-01-14 08:50

    Naive solution:

      target_row = 5
      for num, line in enumerate(d):
          if num == target_row:
              print line["name"]
              break
    

    I removed the intermediate variable score.

    Note that this is non-optimal, as you iterate until you reach the desired row, but I don't know if there is random access to lines in the DictReader.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-14 08:55

    Skipping ahead to the desired line, just as in the other answer, but with slicing on the CSV-reading iterator instead of a manual loop:

    import csv, itertools
    rownum = 20
    colname = "name"
    line = itertools.islice(d, rownum - 1, rownum).next()
    score = line[colname]
    

    (Not the most beautiful code, I know, but that's just to illustrate the point.)

    0 讨论(0)
提交回复
热议问题