Python import csv to list

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

    Using the csv module:

    import csv
    
    with open('file.csv', newline='') as f:
        reader = csv.reader(f)
        data = list(reader)
    
    print(data)
    

    Output:

    [['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]
    

    If you need tuples:

    import csv
    
    with open('file.csv', newline='') as f:
        reader = csv.reader(f)
        data = [tuple(row) for row in reader]
    
    print(data)
    

    Output:

    [('This is the first line', 'Line1'), ('This is the second line', 'Line2'), ('This is the third line', 'Line3')]
    

    Old Python 2 answer, also using the csv module:

    import csv
    with open('file.csv', 'rb') as f:
        reader = csv.reader(f)
        your_list = list(reader)
    
    print your_list
    # [['This is the first line', 'Line1'],
    #  ['This is the second line', 'Line2'],
    #  ['This is the third line', 'Line3']]
    

提交回复
热议问题