if语句后继续读入文件

时间:2014-02-11 01:14:28

标签: python list csv

如果if语句为true,我想继续并将CSV文件阅读器的后四行附加到列表中。如何使用CSV类?

for j in range(3):
    f = open("Trial_"+ str(num) + "_Game_" + str(j) + ".csv")
    reader = csv.reader(f, delimiter=',')
    f.next()
    for line in reader:
        all_decisions.append(map(int,line))
        if all_decisions[-1][4] == 1: 
            for k in range(4):
                # append the next line in the reader to all_decisions here

1 个答案:

答案 0 :(得分:3)

创建一个iter的{​​{1}},直接循环播放reader而不是reader,然后在next()iter拨打if reader_iter = iter(reader) # <-- using this in both loops for line in reader_iter: all_decisions.append(map(int, line)) if all_decisions[-1][4] != 1: for _, kline in zip(range(4), reader_iter): # zip stops after range(4). we only need kline all_decisions.append(kline) 声明:

iter

通过制作reader_iter next(),您可以在range(4)循环中调用reader以及在主循环中调用(自动)


修改:根据@JonClements的评论,iter已经是islice,因此在其上使用for line in reader: all_decisions.append(map(int, line)) if all_decisions[-1][4] != 1: all_decisions.extend(islice(reader, 4)) 将自动生效:

{{1}}

虽然我的第一个例子仍然是关于iterables如何工作的一个很好的练习:)