【发布时间】:2018-05-15 04:13:59
【问题描述】:
基本上,我有一个指示 CSV 文件行号的列表,我想连接列表后面的行。
例如,我的列表是[0, 7, 10, 11, 27, 31]
这意味着我想将我的行从第 1 行到第 7 行连接成一行。
第 8 到 10 行改为单行。
第 11 到 11 行(同一行,所以它什么也不做)
第 12 到 27 行
第 28 到 31 行
我尝试过使用 itertools 中的 while 循环和 islice。但是,我只得到第 1 行到第 7 行的输出。 这是我的代码。
import csv
from itertools import islice
with open('csvtest.csv', 'rb') as f:
reader = csv.reader(f)
#row1 = next(reader)
merged = []
list = [0, 7, 10, 11, 27, 31]
x=0
while x < len(list):
for line in islice(f, list[x], list[x+1]):
#print line1
line = line.rstrip()
merged.append(line)
x += 1
print merged #gives ['fsfs', 'sf', '1231', 'afsa', '', '', 'asfasfsaf;0'] which is lines 1 to 7
谁能告诉我我的 while 循环发生了什么?还是附加列表部分有问题?
【问题讨论】:
标签: python python-2.7 csv