如何使用Python读写CSV文件?

发布于 2021-02-02 23:21:20

我有一个example.csv包含内容的文件

1,"A towel,",1.0
42," it says, ",2.0
1337,is about the most ,-1
0,massively useful thing ,123
-2,an interstellar hitchhiker can have.,3

如何example.csv使用Python 阅读?

同样,如果我有

data = [(1, "A towel,", 1.0),
        (42, " it says, ", 2.0),
        (1337, "is about the most ", -1),
        (0, "massively useful thing ", 123),
        (-2, "an interstellar hitchhiker can have.", 3)]

如何data使用Python 写入CSV文件?

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

    以下是一些最小的完整示例,这些示例如何读取CSV文件以及如何使用Python编写CSV文件。

    Python 2 + 3:读取CSV文件

    Python

    # -*- coding: utf-8 -*-
    
    import csv
    import sys
    
    # Define data
    data = [(1, "A towel,", 1.0),
            (42, " it says, ", 2.0),
            (1337, "is about the most ", -1),
            (0, "massively useful thing ", 123),
            (-2, "an interstellar hitchhiker can have.", 3)]
    
    # Write CSV file
    kwargs = {'newline': ''}
    mode = 'w'
    if sys.version_info < (3, 0):
        kwargs.pop('newline', None)
        mode = 'wb'
    
    with open('test.csv', mode, **kwargs) as fp:
        writer = csv.writer(fp, delimiter=',')
        # writer.writerow(["your", "header", "foo"])  # write header
        writer.writerows(data)
    
    # Read CSV file
    kwargs = {'newline': ''}
    mode = 'r'
    if sys.version_info < (3, 0):
        kwargs.pop('newline', None)
        mode = 'rb'
    with open('test.csv', mode, **kwargs) as fp:
        reader = csv.reader(fp, delimiter=',', quotechar='"')
        # next(reader, None)  # skip the headers
        data_read = [row for row in reader]
    
    print(data_read)
    

    之后,的内容data_read是

    [['1', 'A towel,', '1.0'],
     ['42', ' it says, ', '2.0'],
     ['1337', 'is about the most ', '-1'],
     ['0', 'massively useful thing ', '123'],
     ['-2', 'an interstellar hitchhiker can have.', '3']]
    

    Unicode和Python 2.X

    如果要编写Unicode,则必须安装unicodecsv。千万不能用打开文件codecs.open,而只是用open。用写

    import unicodecsv as csv
    # Write CSV file
    with open('test.csv', 'w', newline='') as fp:
        writer = csv.writer(fp, encoding='utf-8')
        # writer.writerow(["your", "header", "foo"])  # write header
        writer.writerows(data)
    


知识点
面圈网VIP题库

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

去下载看看