Python import csv to list

后端 未结 13 1093
后悔当初
后悔当初 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:54

    Extending your requirements a bit and assuming you do not care about the order of lines and want to get them grouped under categories, the following solution may work for you:

    >>> fname = "lines.txt"
    >>> from collections import defaultdict
    >>> dct = defaultdict(list)
    >>> with open(fname) as f:
    ...     for line in f:
    ...         text, cat = line.rstrip("\n").split(",", 1)
    ...         dct[cat].append(text)
    ...
    >>> dct
    defaultdict(, {' CatA': ['This is the first line', 'This is the another line'], ' CatC': ['This is the third line'], ' CatB': ['This is the second line', 'This is the last line']})
    

    This way you get all relevant lines available in the dictionary under key being the category.

提交回复
热议问题