【问题标题】:Concatenating rows in CSV file Using islice使用 islice 连接 CSV 文件中的行
【发布时间】: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


    【解决方案1】:

    我已经修复了代码,基本上你需要改变如何实现islice

    根据新信息更新答案。

    import csv
    from itertools import islice
    
    with open('output2.csv','wb') as w:
        writer = csv.writer(w)
    
        delimiter_list = []
        merged = []
    
    
        with open('csvtest.csv', 'rb') as f:
            reader = csv.reader(f)
    
            for num, line in enumerate(reader, 1):
                line = (" ".join(line))
                if line.endswith(';0'):
                        #print 'found at line:', num
                    delimiter_list.append(num)
    
        with open('csvtest.csv', 'rb') as f:
            x=0
            while x < len(delimiter_list)-1:
                row = []
                # islice(f,N) returns next N lines  
                for line in islice(f, delimiter_list[x+1]-delimiter_list[x]):
                    line = line.rstrip()
                    row.append(line)
                x += 1
                # add each row to final list
                merged.append(row)
        print merged
    
        writer.writerows(merged)
    

    【讨论】:

      猜你喜欢
      • 2019-03-29
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2021-10-21
      • 2020-11-03
      • 1970-01-01
      • 2017-05-05
      • 2017-08-21
      相关资源
      最近更新 更多