当前位置:   article > 正文

Python的csv文件写入注意点writerow和writerows时--------------里面是用()还是[]_write_row

write_row

第一种写入,用的是()
注意这里面的writerows使用的()—开始我因为最后得到的行是tuple元组,最后经过实验发现,仍旧是list列表

with open(r'D:\lagua\study\coding\pythonPractice\test.csv','w',newline='',encoding = 'utf-8') as f:
    l1 = [0,1,2]
    l2 = [1,2,3]
    l3 = [2,3,4]
    writer = csv.writer(f)
    writer.writerows((l1,l2,l3))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

第二种写入,用的是[]

with open(r'D:\lagua\study\coding\pythonPractice\test.csv','w',newline='',encoding = 'utf-8') as f:
    l1 = [0,1,2]
    l2 = [1,2,3]
    l3 = [2,3,4]
    writer = csv.writer(f)
    writer.writerows([l1,l2,l3])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

经过实验,发现两者得到的均为list–指的是取数据时,第一行是list
测试代码如下

with open(r'D:\lagua\study\coding\pythonPractice\test.csv','r',newline='',encoding = 'utf-8') as f:
    reader = csv.reader(f)
    temp = []
    for line in reader:
        temp.append(line)
print(isinstance(temp[0],list))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

结果为True

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/347711
推荐阅读
相关标签
  

闽ICP备14008679号