Python将csv导入列表

发布于 2021-02-02 23:17:38

我有一个大约有2000条记录的CSV文件。

每个记录都有一个字符串和一个类别:

This is the first line,Line1
This is the second line,Line2
This is the third line,Line3

我需要将此文件读入如下列表:

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

如何使用Python将CSV导入到我需要的列表中?

关注者
0
被浏览
86
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    使用csv模块:

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

    输出:

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

    如果你需要元组:

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

    输出:

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

    旧的Python 2答案,也使用csv模块:

    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']]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看