【问题标题】:Python inserting list of integers into CSV column after other dataPython在其他数据之后将整数列表插入CSV列
【发布时间】:2013-02-09 16:18:20
【问题描述】:

我正在尝试在现有数据之后将新列插入 CSV 文件。例如,我的 CSV 文件当前包含:

   Heading 1     Heading 2
   1 
   1
   0
   2
   1
   0

我有一个整数列表,格式为:

 [1,0,1,2,1,2,1,1]

如何将此列表插入 CSV 文件的“Header 2”下?

到目前为止,我所能实现的只是在当前数据下添加新的整数列表,例如:

   Heading 1     Heading 2
   1 
   1
   0
   2
   1
   0
   1
   0
   1
   2
   1
   2
   1
   1

使用代码:

 #Open CSV file
 with open('C:\Data.csv','wb') as g:
            #New writer
    gw = csv.writer(g)
            #Add headings
    gw.writerow(["Heading 1","Heading 2"])
            #Write First list of data to heading 1 (orgList)
    gw.writerows([orgList[item]] for item in column)
            #For each value in new integer list, add row to CSV
    for val in newList:
        gw.writerow([val])

【问题讨论】:

    标签: python list csv


    【解决方案1】:

    这是一个纠正错误的代码:

    import csv
    from itertools import izip_longest
    
    
    # Creating a CSV file
    with open(r'Data.csv','wb') as f:
        fw = csv.writer(f)
        fw.writerows( (('Heading 1', 'Heading 2'),
                       ('1'),
                       ('1'),
                       ('0'),
                       ('2'),
                       ('1'),
                       ('0'))   )
    
    
    print "The CSV file at start, read by a csv.reader :\n"
    with open(r'Data.csv','rb') as f:
        fr = csv.reader(f)
        print '\n'.join(map(repr,fr))
    
    
    print '\n------------------------------------------'
    newdata = [10,0,10,20,10,20,10,10]
    
    with open(r'Data.csv','rb') as f:
        fr = csv.reader(f)
        newrows = [fr.next()]
        newrows += (a+[b] for a,b in izip_longest(fr, newdata,
                                                  fillvalue=[0]))
    
    print 'newrows\n',newrows
    
    with open(r'Data.csv', 'wb') as f:
         csv.writer(f).writerows(newrows)
    print '------------------------------------------\n'
    
    
    print "The new CSV file created, read by a csv.reader :\n"
    with open(r'Data.csv','rb') as f:
        fr = csv.reader(f)
        print '\n'.join(map(repr,fr))
    

    它显示:

    The CSV file at start, read by a csv.reader :
    
    ['Heading 1', 'Heading 2']
    ['1']
    ['1']
    ['0']
    ['2']
    ['1']
    ['0']
    
    ------------------------------------------
    newrows
    [['Heading 1', 'Heading 2'], ['1', 10], ['1', 0], ['0', 10], ['2', 20], ['1', 10], ['0', 20], [0, 10], [0, 10]]
    ------------------------------------------
    
    The new CSV file created, read by a csv.reader :
    
    ['Heading 1', 'Heading 2']
    ['1', '10']
    ['1', '0']
    ['0', '10']
    ['2', '20']
    ['1', '10']
    ['0', '20']
    ['0', '10']
    ['0', '10']
    

    编辑

    更简洁

    import csv
    from itertools import izip_longest
    from os import remove,rename
    
    # Creating a CSV file
    with open(r'Data.csv','wb') as f:
        fw = csv.writer(f)
        fw.writerows( (('Heading 1', 'Heading 2'),
                       ('1'),
                       ('1'),
                       ('0'),
                       ('2'),
                       ('1'),
                       ('0'))   )
    
    print "The CSV file at start, read by a csv.reader :\n"
    with open(r'Data.csv','rb') as f:
        print '\n'.join(map(repr,csv.reader(f)))
    
    
    #------------------------------------------
    newdata = [10,0,10,20,10,20,10,10]
    
    with open(r'Data.csv','rb') as f, open(r'newData.csv','wb') as g:
        fr = csv.reader(f)
        gw = csv.writer(g)
        gw.writerow(fr.next())
        gw.writerows( a+[b] for a,b in izip_longest(fr, newdata,
                                                    fillvalue=[0]) )
    remove (r'Data.csv')
    rename (r'newData.csv',r'Data.csv')
    
    #------------------------------------------
    
    print "The new CSV file created, read by a csv.reader :\n"
    with open(r'Data.csv','rb') as f:
        print '\n'.join(map(repr,csv.reader(f)))
    

    【讨论】:

      【解决方案2】:

      未经测试:

      import csv
      from itertools import izip_longest
      
      some_ints = [1,0,1,2,1,2,1,1]
      
      with open('input') as fin, open('output', 'w') as fout:
          csvin = csv.reader(fin)
          csvout = csv.writer(fout)
          cols = izip_longest(csvin, some_ints, fillvalue='')
          csvout.writerows(cols)
      

      【讨论】:

        【解决方案3】:

        你有两个相关的问题:

        • 写入您正在阅读的同一文件
        • 仅发出新数据,而不是包含新旧数据的新行。

        首先将数据读入内存:

        with open(r'C:\Data.csv','rb') as f:
            rows = list(csv.reader(f))
        

        然后将元组列表转换为具有新数据的新元组列表:

        newdata = [1,0,1,2,1,2,1,1]
        newrows = [rows[0]]            # keep the current two headers
        newrows += izip_longest(rows[1:], newdata, fillvalue=0)
        

        最后,将数据写回磁盘:

        with open(r'C:\Data.csv', 'wb') as f:
             csv.writer(f).writerows(newrows)
        

        【讨论】:

        • 这行得通。尽管它将 CSV 第 1 列中的项目放入括号中,例如标题 1(第 1 行)= ['1'] 标题 2(第 1 行)= 1
        猜你喜欢
        • 2012-08-31
        • 1970-01-01
        • 2021-06-27
        • 1970-01-01
        • 1970-01-01
        • 2018-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多