0

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

   Heading 1     Heading 2
   1 
   1
   0
   2
   1
   0

我有一个格式的整数列表:

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

如何将此列表插入到“标题 2”下的 CSV 文件中?

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

   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])
4

3 回答 3

1

未经测试:

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)
于 2013-02-09T16:22:18.357 回答
1

你有两个相关的问题:

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

首先将数据读入内存:

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)
于 2013-02-09T16:52:14.457 回答
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)))
于 2013-02-09T23:18:38.820 回答