怎么在Python项目中读写csv文件

怎么在Python项目中读写csv文件?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

新建test.csv

1.写

import csv
with open("test.csv","w",encoding='utf8') as csvfile:
  writer=csv.writer(csvfile)
  writer.writerow(["index","a_name","b_name"])
  writer.writerows([[0,'a1','b1'],[1,'a2','b2'],[2,'a3','b3']])

直接使用这种写法会导致文件每一行后面会多一个空行

解决的方法

用python3来写wirterow时,打开文件时使用w模式,然后带上newline=''

import csv
with open("test.csv","w",encoding='utf8',newline='') as csvfile:
  writer=csv.writer(csvfile)
  writer.writerow(["index","a_name","b_name"])
  writer.writerows([[0,'a1','b1'],[1,'a2','b2'],[2,'a3','b3']])

2.读

import csv
with open("test.csv","r") as csvfile:
  reader=csv.reader(csvfile)
  for line in reader:
    print(line)

怎么在Python项目中读写csv文件

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注行业资讯频道,感谢您对亿速云的支持。