Loading

Python处理csv文件

一、逐行写入csv

import csv

subject = ["语文","数学","英语","生物"]
score_first = [75, 90, 70, 77]
score_second = [80, 90, 80, 80]
score_third = [85, 90, 75, 88]
score_fourth = [90, 90, 80, 90]
with open ("test.csv", 'w', encoding="utf8", newline="") as f:
    # 基于文件对象f构建csv写入对象
    csv_write = csv.writer(f)
    # 逐行写入
    csv_write.writerow(subject)
    csv_write.writerow (score_first)
    csv_write.writerow (score_second)
    csv_write.writerow (score_third)
    csv_write.writerow (score_fourth)

二、逐行读取csv

with open ("test.csv", 'r', encoding="utf8", newline="") as f:
    # 基于文件对象f构建读取对象
    csv_read = csv.reader(f)
    # 逐行读取
    for row in csv_read:
        print (row)

posted @ 2022-05-08 10:51  eiSouthBoy  阅读(277)  评论(0)    收藏  举报