原创

Python操作csv文件

引入csv模块

Python自带csv操作模块,不需要单独安装

import csv

读取csv文件

import csv

with open("file.csv",encoding="utf-8") as f:
    reads = csv.reader(f) #csv读取
    header = next(reads)  # 读取csv文件头
    for rows in reads: # 遍历数据行,数据是列表
        print(rows[0]) #打印第一列数据 

写入csv文件

import csv

headers = ["序号","名称"]

row = [
    ["1","aaa"],
    ["2","bbb"]
]

with open("123.csv","w",encoding="utf-8") as f:
    w_csv = csv.writer(f)
    w_csv.writerow(headers)
    w_csv.writerows(row)

windows写入文件可能会出现空行问题,需要加 newline参数

import csv

headers = ["序号","名称"]

row = [
    ["1","aaa"],
    ["2","bbb"]
]

with open("123.csv","w",encoding="utf-8",newline='') as f:
    w_csv = csv.writer(f)
    w_csv.writerow(headers)
    w_csv.writerows(row)


正文到此结束
评论

登录后才能发表评论 登录/注册

0评论
  • 还没有评论,快来抢沙发吧!