Python import csv to list

后端 未结 13 1084
后悔当初
后悔当初 2020-11-22 06:15

I have a CSV file with about 2000 records.

Each record has a string, and a category to it:

This is the firs         


        
13条回答
  •  隐瞒了意图╮
    2020-11-22 06:52

    Next is a piece of code which uses csv module but extracts file.csv contents to a list of dicts using the first line which is a header of csv table

    import csv
    def csv2dicts(filename):
      with open(filename, 'rb') as f:
        reader = csv.reader(f)
        lines = list(reader)
        if len(lines) < 2: return None
        names = lines[0]
        if len(names) < 1: return None
        dicts = []
        for values in lines[1:]:
          if len(values) != len(names): return None
          d = {}
          for i,_ in enumerate(names):
            d[names[i]] = values[i]
          dicts.append(d)
        return dicts
      return None
    
    if __name__ == '__main__':
      your_list = csv2dicts('file.csv')
      print your_list
    

提交回复
热议问题