2

CSV__04--python使用迭代器读取csv文件出现读取结果为空的解决办法

 1 year ago
source link: https://blog.51cto.com/husheng/5918791
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Table of Contents

1 迭代器的概念

迭代器(iterator)有时又称光标(cursor)是程序设计的软件设计模式,可在容器对象(container,例如链表或数组)上遍访的接口。

2 迭代器的特点

  • 强制性:必须将元素从迭代器中取出后,才能使用元素;
  • 一次性:取出以后该元素就从迭代器中删除,无法二次遍历;
  • 未知性:容器内部元素无法直接定位,只能遍历按序取出。

3 问题解决

迭代器每次使用后会迭代至末尾

当我们再次使用这个迭代器进行for循环读取时得到的结果自然为空

解决方法只需新建一个迭代器即可。

迭代器:IndexError: list index out of range

import csv

#读T1
reader = csv.reader(open('结果1.csv','rt'))
column1 = [row1[0:9] for row1 in reader]
# 写入标题
with open('demo2.csv', 'w', encoding='UTF8', newline='') as f0:
    writer0 = csv.writer(f0)
    # write the header
    writer0.writerow(column1[0])

#读T2
reader2 = csv.reader(open('结果1.csv', 'rt'))
column2 = [row2[0:3]+row2[9:15] for row2 in reader2]

#读T3
reader3 = csv.reader(open('结果1.csv', 'rt'))
column3 = [row3[0:3]+row3[15:21] for row3 in reader3]


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK