csv模块也是一个python的内置模块,该模块处理的是csv文件的读取和存档
csv模块中的reader类和writer类可用于读写序列化的数据。也可使用DictReader类和DictWriter类以字典的形式读写数据。这个我们仅使用后面两个类
csv.rader(fq)
该函数读取文件csv文件,fq为csv文件对象,返回的是一个reader对象(迭代器),具体用法如下:
import csv # 读取csv文件 with open("1.csv", "r") as f: text = csv.reader(f) # 返回的是一个迭代器,每次迭代的一行内容 next(text) # 去掉第一行 for data in text: print(data)
csv.writer(fq)
该函数用于往csv文件写入数据,fq是一个csv文件对象(该文件打开时一定要加上newline="",不然数据会出现空行),该函数返回的是一个writer对象,该对象负责将传入数据写入csv文件(函数writerow()和函数writerows()),写入的数据应该是数组或列表类型的
import csv header = ["name", "age", "sex"] data = [["python", "21", "man"], ["java", "30", "man"]] # 写scv文件 with open("1.csv", "w", newline="", encoding="utf8") as f1: writer = csv.writer(f1) writer.writerow(header) writer.writerows(data)
csv.DictReader(fp)
fp是一个csv文件对象,该函数返回的是一个DictReader对象(迭代器),且是字典类型
import csv with open("1.csv", "r") as f: reader = csv.DictReader(f) for data in reader: print(data)
csv.DictWriter(fq,headers)
fq是一个csv文件对象,headers是一个数组或列表(csv文件的头),该函数返回的是一个DictWriter对象,该对象在操作上类似常规 writer,但会将字典映射到输出行
import csv headers = ["name", "age", "sex"] dict_data = [ {"name": "lili", "age": "1", "sex": "man"}, {"name": "haha", "age": "2", "sex": "man"}, {"name": "wawa", "age": "4", "sex": "woman"} ] with open("2.csv", "w", newline="", encoding="utf8") as f: writer = csv.DictWriter(f, headers) writer.writeheader() writer.writerows(dict_data)