首页 > 技术文章 > Python 读取与写入CSV文件(后缀名.csv)

rainbow-tan 2020-07-03 14:26 原文

测试csv数据如下图:

csv名字:forreaddata.csv

1、读取

# -*- encoding=utf-8 -*-

import csv

if __name__ == '__main__':
    pass
    filename = 'CSV/forreaddata.csv'
    with open(filename, 'r') as f:
        csv_data = csv.reader(f)
        for data in csv_data:
            print(data)

运行结果

['height', 'weight', 'sex']
['160', '95', '1']
['165', '100', '1']
['166', '95', '1']
['170', '150', '1']
...
['175', '90', '0']
['178', '95', '0']
['169', '90', '0']
['164', '90', '0']
['170', '90', '0']

 2、写入

# -*- encoding=utf-8 -*-

import csv

if __name__ == '__main__':
    pass
    write_filename = 'CSV/forwritedta.csv'
    # 如果不指定newline='',则每写入一行将有一空行被写入
    with open(write_filename, 'w', newline='') as f:
        f_csv = csv.writer(f)
        f_csv.writerow(['height', 'weight', 'sex'])  # 写入一行
        data = [['160', '95', '1'], ['165', '100', '1'], ['166', '95', '1']]
        f_csv.writerows(data)  # 写入多行

运行结果

推荐阅读