csv即Comma Separate Values,有时也称字符分隔符,因为分隔字符也可以不是逗号,其文件以纯文本形式存储表格数据(数字和文本)。经常用来作为不同程度之间的数据交互的格式。
import csv
with open("demo4.csv","w",newline="") as f: #打开demo4.csv文件,并进入写模式,由于换行符为默认值,可以设置newline=""
datawriter = csv.writer(f)
datawriter.writerow(["name","age","gender"]) #逐行写入
datawriter.writerow(["amy","18","female"])
datawriter.writerows([["name","age","gender"],["amy","18","female"]]) #多行写入
with open("demo4.csv","r") as f : # 打开demo4.csv文件,并进入读模式
datareader = csv.reader(f) # 创建csv读对象
print(next(datareader)) # 通过迭代器逐行读出
print(next(datareader))
# 通过for循环一次性读出
for i in datareader:
print(i)