一、参考链接
https://docs.python.org/zh-cn/3/library/csv.html?highlight=csv#module-csv
二、写入csv文件
1、方式一
def test_write(self):
with open('./data.csv','w',encoding='utf-8') as f:
cw= csv.writer(f)
cw.writerow(['test','csv','demo'])
2、方式二
def test_dict_writer(self):
'''
参数newline是用来控制文本模式之下,一行的结束字符。可以是None,’’,\n,\r,\r\n等。
不加写入的则为如下格式:
username,password
xian1,test1234
xian2,test1234
xian3,test1234
:return:
'''
with open('./data.csv','w',encoding='utf-8',newline='') as f:
filesnames=['username','password']
cw=csv.DictWriter(f,fieldnames=filesnames)
cw.writeheader()
cw.writerow({'username':'xian1','password':'test1234'})
cw.writerow({'username':'xian2','password':'test1234'})
cw.writerow({'username':'xian3','password':'test1234'})
三、读取csv文件
data.csv文件如下:
username,password
xian1,test1234
xian2,test1234
xian3,test1234
1、方式一
def test_read(self):
with open('./data.csv','r',encoding='utf-8') as f:
cr=csv.reader(f)
for row in cr:
print(row)
2、方式二
def test_dict_reader(self):
with open('./data.csv','r',encoding='utf-8') as f:
cr=csv.DictReader(f)
for row in cr:
print(row['username'],row['password'])