1、读取 csv 文件中的数据
- reader() 返回一个 reader 对象,利用该对象遍历 csv 文件中的行
- 从 csv 文件中读取的每一行都作为字符串列表返回
import csv # data_info.csv 是文件名称 with open("data_info.csv","r") as f: data = csv.reader(f) for d in data: if d[0] == "username": # 过滤第一行 title continue print(d) # 结果如下 ['admin', '123456'] ['guest', '234567']
2、写入 csv 文件数据
- writer(myFile) 返回 writer 对象 myWriter
- writerow() 方法是一行一行写入,writerows 方法是一次写入多行
- 注意:如果文件 'data_info.csv' 事先存在,调用 writer 函数会先清空原文件中的文本,再执行 writerow/writerows 方法。
# 使用 writerow() 逐行写入 import csv # newline="" 消除每写入一行就出现一行空单元格效果 with open("data_info.csv","w",newline="") as f: myWrite = csv.writer(f) myWrite.writerow(["username","password"]) myWrite.writerow(["admin","123456"]) myWrite.writerow(["guest","234567"])
# 使用 writerows() 批量写入 import csv with open("data_info.csv","w",newline="") as f: myWrite = csv.writer(f) # 每行数据放在一个数组中 data_list = [["username","password"],["admin","123456"],["guest","234567"]] myWrite.writerows(data_list)